0
0
ExpressHow-ToBeginner · 3 min read

How to Use CORS in Express: Simple Setup Guide

To use cors in Express, install the cors package and add it as middleware with app.use(cors()). This enables cross-origin resource sharing, allowing your server to accept requests from different domains.
📐

Syntax

The cors middleware is used by importing it and then applying it to your Express app with app.use(cors()). You can pass options to customize which origins or methods are allowed.

  • cors(): Enables CORS with default settings (allows all origins).
  • cors(options): Customize CORS behavior, e.g., restrict origins.
  • app.use(): Adds middleware to Express request handling.
javascript
import express from 'express';
import cors from 'cors';

const app = express();

// Enable CORS for all routes and origins
app.use(cors());

// Or with options
// app.use(cors({ origin: 'https://example.com' }));
💻

Example

This example shows a simple Express server that uses cors middleware to allow requests from any origin. It responds with a JSON message on the root route.

javascript
import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors());

app.get('/', (req, res) => {
  res.json({ message: 'CORS enabled for all origins!' });
});

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

Common Pitfalls

Common mistakes when using CORS in Express include:

  • Not installing the cors package before importing it.
  • Forgetting to use app.use(cors()) before defining routes.
  • Using restrictive options without allowing the needed origins, causing blocked requests.
  • Trying to set CORS headers manually instead of using the middleware, which can be error-prone.
javascript
/* Wrong: Missing cors middleware */
app.get('/', (req, res) => {
  res.json({ message: 'No CORS headers set' });
});

/* Right: Use cors middleware before routes */
import cors from 'cors';
app.use(cors());
app.get('/', (req, res) => {
  res.json({ message: 'CORS enabled' });
});
📊

Quick Reference

Here is a quick summary of key points when using CORS in Express:

FeatureDescription
Install packagenpm install cors
Import middlewareimport cors from 'cors'
Enable globallyapp.use(cors())
Restrict originsapp.use(cors({ origin: 'https://example.com' }))
Use before routesPlace middleware before route handlers

Key Takeaways

Install and import the cors package to enable CORS in Express.
Use app.use(cors()) before defining routes to allow cross-origin requests.
Customize CORS with options to restrict allowed origins if needed.
Avoid setting CORS headers manually; use the cors middleware instead.
Test your server to ensure CORS headers are correctly sent in responses.