Examples of CORS with Node.js and Koa framework

Learn how to implement CORS in APIs using Node.js and Koa framework with these practical examples.
By Jamie

Understanding CORS in APIs

Cross-Origin Resource Sharing (CORS) is a security feature implemented in web browsers that restricts web pages from making requests to a different domain than the one that served the web page. When building APIs, especially with frameworks like Node.js and Koa, it is crucial to handle CORS properly to allow or restrict requests from different origins. Here are three practical examples of implementing CORS in Node.js using the Koa framework.

Example 1: Basic CORS Setup

In this example, we will set up a basic CORS configuration that allows requests from any origin. This is useful for development purposes or when your API is designed to be open to all clients.

First, install the @koa/cors package:

npm install @koa/cors

Next, you can create a simple Koa server with CORS enabled:

const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();

app.use(cors()); // Enable CORS for all requests

app.use(ctx => {
  ctx.body = 'CORS is enabled!';
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This code sets up a basic Koa server that will respond to requests from any origin. Simply run your server and make a request to test CORS functionality.

Notes:

  • This configuration should be used cautiously in a production environment as it allows requests from any origin.
  • For production, consider specifying allowed origins for enhanced security.

Example 2: Restricting CORS to Specific Origins

In this example, we will configure CORS to allow requests only from specific origins. This ensures that only trusted domains can access your API.

const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();

const allowedOrigins = ['http://example.com', 'http://another-example.com'];

app.use(cors({
  origin: (ctx) => {
    const origin = ctx.request.headers.origin;
    if (allowedOrigins.includes(origin)) {
      return origin; // Allow the request
    }
    return null; // Block the request
  }
}));

app.use(ctx => {
  ctx.body = 'CORS is restricted to specific origins!';
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

In this example, the server will only respond to requests from http://example.com and http://another-example.com. Any other requests will be blocked.

Notes:

  • You can add or remove origins from the allowedOrigins array as needed.
  • Ensure to handle preflight requests for HTTP methods like PUT and DELETE by responding with appropriate headers.

Example 3: Enabling Credentials

In this example, we will enable CORS to allow credentials (like cookies or HTTP authentication) to be sent in requests from specific origins. This is common in scenarios where user authentication is required.

const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();

const allowedOrigins = ['http://example.com'];

app.use(cors({
  origin: (ctx) => {
    const origin = ctx.request.headers.origin;
    if (allowedOrigins.includes(origin)) {
      return origin; // Allow the request
    }
    return null; // Block the request
  },
  credentials: true // Allow credentials
}));

app.use(ctx => {
  ctx.body = 'CORS with credentials is enabled!';
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This implementation allows cookies and credentials to be included in requests made from http://example.com, enhancing the security and usability of your API in scenarios requiring user sessions.

Notes:

  • Make sure your frontend correctly handles credentials with fetch or XMLHttpRequest by setting the credentials option to include.
  • Always validate and sanitize incoming requests to prevent security vulnerabilities.