Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To configure CORS preflight in AdonisJS v5.9.0, follow these steps:

  1. Install the @adonisjs/cors package using npm:
npm i @adonisjs/cors@latest
  1. Register the middleware in the start/kernel.ts file:
import corsMiddleware from '@adonisjs/cors'

...

const serverMiddleware = [
  ...
  /*
  |--------------------------------------------------------------------------
  | Cross-Origin Resource Sharing (CORS)
  |--------------------------------------------------------------------------
  |
  | Enables CORS middleware which will handle CORS for you.
  | This is required when running on a different domain than the API.
  |
  */
  corsMiddleware({ origin: '*' }),
]
  1. Configure the options for the middleware by passing it an options object. In this example, { origin: '*' } means that any origin is allowed. You can also restrict allowed origins to specific domains.
import corsMiddleware from '@adonisjs/cors'

...

const serverMiddleware = [
  ...
  corsMiddleware({
    origin: (requestOrigin, callback) => {
      if (requestOrigin && requestOrigin.startsWith('https://example.com')) {
        return callback(null, true)
      }

      return callback(new Error('Not allowed by CORS'))
    },
    methods: ['GET', 'POST'],
    headers: true,
    exposedHeaders: [],
    credentials: true,
    maxAge: 90,
  }),
]
  1. Test your API by sending a CORS request from a different domain:
fetch('https://your-api-domain.com', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Request-Headers': 'X-Custom-Header',
    'Access-Control-Request-Method': 'POST',
  },
  mode: 'cors',
})