CORS Configuration v8.3.0

Configure Cross-Origin Resource Sharing (CORS) for your API endpoints with enhanced options in Novaxjs2 v8.3.0.

Basic Setup

app.cors({
  origins: ['https://example.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  headers: ['Content-Type', 'Authorization'],
  credentials: true
});

Allow All Origins

app.cors({
  origins: ['*'],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  headers: ['Content-Type', 'Authorization', 'X-Requested-With']
});

Dynamic Origin Validation

app.cors({
  origins: (origin, callback) => {
    // Custom logic to validate origin
    const allowedOrigins = ['https://example.com', 'https://app.example.com'];
    if (allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST'],
  headers: ['Content-Type']
});

Options

OptionDescriptionTypeDefault
originsAllowed origins (array or function)Array|Function[]
methodsAllowed HTTP methodsArray['GET','POST','PUT','DELETE']
headersAllowed headersArray['Content-Type']
credentialsAllow credentialsBooleanfalse
maxAgeMax age in seconds for preflight requestsNumber86400 (24 hours)

Preflight Request Handling

Novaxjs2 v8.3.0 automatically handles OPTIONS requests for CORS preflight checks. You don't need to define OPTIONS routes manually.

Best Practices

Restrict Origins

Always specify allowed origins instead of using wildcard (*) in production.

Limit Methods

Only allow HTTP methods that your API actually uses.

Specify Headers

Explicitly list allowed headers to prevent unauthorized access.

Use Credentials Carefully

Only enable credentials when necessary and with specific origins.