Using CORS in Next.js to handle cross-origin requests

Over the past few years, Next.js has become a go-to framework not only for frontend development, but also for robust API development. When building APIs, it is critical to spend some time on Cross-Origin Resource Sharing (CORS).

What is CORS?

CORS serves as a security mechanism empowering a server to dictate which origins can access and load resources in a web browser. Here, an “origin” refers to the amalgamation of the protocol, domain, and port number from which a request originates.

In essence, CORS acts as a safeguard enforced by web browsers to impose restrictions on cross-origin requests. Its primary aim is to ensure user security by preventing unauthorized access to resources and data.

The implementation of CORS involves the exchange of specific HTTP headers between browsers and servers.

Prior to initiating certain types of cross-origin requests, the browser dispatches a preflight request to the server using the HTTP OPTIONS method. The server then responds with CORS headers, signaling whether the cross-origin request should be allowed or denied.

If the preflight request proves successful, the actual cross-origin request is executed by the browser. Otherwise, it is thwarted due to a CORS policy error.

The main CORS headers include:

  • Access-Control-Allow-Origin — Specifies the origin that has access to the resource
  • Access-Control-Allow-Methods — Added to the preflight response to indicate the permitted HTTP methods, such as GETPOSTPUT, etc.
  • Access-Control-Allow-Headers — Returned in response to a preflight request to specify the HTTP headers that are allowed in the current request
  • Access-Control-Allow-Credentials — Indicates whether the browser should include credentials such as cookies or HTTP authentication in the cross-origin request

CORS allows frontend applications to access resources from a different domain, ensuring secure cross-origin communication. By default, Next.js relies on a same-origin approach, imposing a strict policy. If you want to change that, you must configure it manually.

Addressing CORS issues in Next.js involves implementing specific strategies to manage cross-origin requests. One common approach is to configure the server to include the necessary CORS headers. Below are steps you can take to resolve CORS issues in Next.js:

Install the necessary packages:

Make sure you have the required packages installed. You can use cors middleware to handle CORS headers.

npm install cors

Create a custom server:

In Next.js, you can create a custom server to handle advanced server configurations. Create a server.js file in your project root.

// server.js
const express = require('express');
const next = require('next');
const cors = require('cors');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  // Use CORS middleware
  server.use(cors());

  // Your other routes
  server.get('/your-route', (req, res) => {
    return app.render(req, res, '/your-page', req.query);
  });

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Update your package.json scripts:

Modify your package.json to use the custom server.

{
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js"
  }
}

Run your Next.js app:

Start your app using the custom server:

npm run dev

For Production

npm run build
npm start