• Documentation
  • /
  • Next.js Firebase
  • /
  • Enable CORS

Enable CORS

Enabling CORS is required if you want to allow serving HTTP requests to external clients. For example, if you want to expose an API to some consumers: JS libraries, headless clients, and so on.

To enable CORS, you can use the with-cors and call it in your handler:

import withCors from '~/core/middleware/with-cors';

function apiHandler(
  req: NextApiRequest,
  res: NextApiResponse
) {
    withCors(res);

    // your logic
}

export default apiHandler;

Additionally, you need to respond to OPTIONS request appropriately.

export function loader({ request }: LoaderArgs) {
  withCors();

  if (request.method === `OPTIONS`) {
     return new Response(null, {
      headers: new Headers({
        // add the method you want to allow
        'Access-Control-Allow-Methods': 'GET'
      })
     });
  }
}

Stay informed with our latest resources for building a SaaS

Subscribe to our newsletter to receive updatesor