CORS Handler

Enabled Set roules for Cross Origin Resource Sharing.


This middleware will help you set your CORS options and it is based on built in H3 CORS functionality

โ„น Read more about Cross Origin Resource Sharing here.

Testing CORS configuration can be done by running one application with NuxtSecurity enabled and creating a second application (that is running on a different port) that will send a request to the first app. Then, a CORS error could be easily observed that proves that CORS is working as expected.

Usage

This middleware is enabled globally by default. You can customize it both globally and per route like following:

nuxt.config.ts
export default defineNuxtConfig({  // Global  security: {    corsHandler: {      // options    }  }  // Per Route  routeRules: {    '/my-secret-route': {      security: {        corsHandler: {          // options        }      }    }  }})

You can also disable the middleware globally or per route by setting corsHandler: false.

Options

CORS handler accepts following configuration options:

interface H3CorsOptions {  origin?: '*' | 'null' | (string | RegExp)[] | ((origin: string) => boolean);  methods?: '*' | HTTPMethod[];  allowHeaders?: '*' | string[];  exposeHeaders?: '*' | string[];  credentials?: boolean;  maxAge?: string | false;  preflight?: {      statusCode?: number;  };}

origin

  • Default: ${serverUrl}

The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.

methods

  • Default: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']

The Access-Control-Allow-Methods response header specifies one or more methods allowed when accessing a resource in response to a preflight request.

allowHeaders

  • Default: -

The Access-Control-Allow-Headers response header is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request.

exposeHeaders

  • Default: -

The Access-Control-Expose-Headers response header allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request.

credentials

  • Default: -

The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to the frontend JavaScript code when the request's credentials mode (Request.credentials) is include.

maxAge

  • Default: -

The Access-Control-Max-Age response header indicates how long the results of a preflight request (that is the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.

preflight.statusCode

  • Default: 204

Status code for preflight request.