HTTP Access Control (CORS) Handler

1.0.1 · abandoned · verified Wed Apr 22

The `access-control` package offers a minimal and straightforward implementation for managing HTTP Access Control (CORS) according to the W3C specification. It is designed as a focused utility for applications needing to handle cross-origin requests, abstracting the complexities of CORS header management. As of its last known release, the package is at version 1.0.1, published over 8 years ago, indicating it is no longer actively maintained. Its core functionality involves configuring allowed origins, HTTP methods, credentials handling, preflight request caching (`maxAge`), and exposing/allowing specific headers. A key differentiator is its direct handling of `OPTIONS` preflight requests and automatic `403 Forbidden` responses for invalid CORS attempts, as well as automatic adjustment of `Access-Control-Allow-Origin` when `*` is combined with `credentials: true` for specification compliance.

Common errors

Warnings

Install

Imports

Quickstart

Illustrates how to configure `access-control` with specific origins and credentials, and integrate the resulting middleware into a Node.js HTTP server to handle CORS preflight requests and secure responses.

'use strict';

const access = require('access-control');
const http = require('http');

// Configure the CORS middleware
const corsHandler = access({
  maxAge: '1 hour',
  credentials: true,
  origins: 'http://example.com'
});

const server = http.createServer((req, res) => {
  // The corsHandler function processes the request and response.
  // If it returns `true`, it means it handled the request (e.g., preflight or error),
  // and no further response is needed from your application logic.
  if (corsHandler(req, res)) {
    return;
  }

  // For valid, non-preflight requests that pass CORS checks, proceed with application logic.
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from a valid CORS request!');
});

server.listen(8080, () => {
  console.log('CORS-enabled server listening on http://localhost:8080');
});

view raw JSON →