Configure Cross-Origin Resource Sharing (CORS)

If your frontend and backend are hosted on different origins you'll need to configure CORS.

🚧

Determine If You Actually Need CORS

CORS is only required when your frontend and backend are hosted on different origins. To be considered the same origin, the scheme, domain and port of the frontend and backend must be the same. For example, if you're hosting both your frontend and backend under origin https://example.com, you don't need to configure CORS and can skip to Testing Login and Logout Flows.

Cross-Origin Resource Sharing (CORS) is a security feature that controls how browsers can request resources from different domains. If your JavaScript frontend and backend servers are hosted on different origins, then you will need to configure CORS to allow your JavaScript frontend to make requests to your backend servers.


Express CORS Configuration

First, install the CORS middleware in your Express server:

npm install cors
yarn add cors
pnpm add cors

Then configure Express to use CORS:

// app.ts
import express from 'express';
import cors from 'cors';

const app = express();

...

app.use(cors({
  origin: '<replace_with_your_frontend_origin>',
  credentials: true // Required for cookies to be sent in requests.
}));

//
// Routes and middlewares come after...
//

...



Frontend Configuration

When making requests from your JavaScript frontend to your backend, ensure you enable credentials to be sent in the request. If credentials aren't enabled, then the session cookie won't be sent in the request.

Axios

axios.defaults.withCredentials = true;

// ...or...

const apiClient = axios.create({
  baseURL: `http://localhost:8080/api`,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  withCredentials: true, // Enable credentials to be sent.
});

Fetch

fetch('http://localhost:8080/api/endpoint', {
  credentials: 'include'
})

Now that CORS is configured, your JavaScript frontend can send requests to your backend server across different origins.


What’s Next

Next let's test the authentication flows to ensure that sessions are properly being managed.