Authorization check during axios/fetch/ajax request CORS issue

Hi!

I have a regular web app and am authenticating users with passport-auth0. I am using axios (and have tried using fetch) to make calls from my app to get data. I based all of my setup on the quickstart guide for node.

I am successfully able to login and logout (using a logout button). I am also using the secured() function on every route. However, when I make axios (or fetch, tried that too) calls to my server, I am running into a CORS error when the session is expired. I understand that there is an issue with ajax calls and redirects, but I am wondering how everyone else is securing these calls. My application works like a SPA in many places, and I want to make sure that the user is not able to get data when their session expires. How can I update my code to either 1) fix the CORS issue or 2) use some other workaround to avoid going through this authorize/redirect/cors issue altogether (something as simple as reloading the page, since this works just fine when the session expires-- takes user to login page)?

The error I’m getting is:

Access to XMLHttpRequest at ‘[Auth0 authorize URL]’ (redirected from ‘http://localhost:3000/[path for data call]’) from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

In most situations the server logic will be independent for routes/paths that immediately serve HTML to the browser and routes/paths that return data (likely JSON) that is consumed by browser-based logic (Javascript).

The first set could react to an expired session with an HTTP redirect (302), while the second set would react to an expired session with an HTTP 401 which the browser-logic could then process as meaning session is expired so I need to ask the user to login (or just reloading the page as that by itself in your case seems to trigger the login due to a server-side check on session and the corresponding 302).

In conclusion, for requests that are meant to be called in a SPA way you can still require the necessary credentials (be it session or something else), but you would return a 401 instead of an immediate redirect to login.