Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that allows or restricts resources requested from a different origin than the one that served the web page. When building APIs with Express, you might encounter situations where you need to configure CORS options to control access from different domains. In this blog, we’ll walk through how to set up custom CORS options in an Express app.
Step 1. Setting Up an Express App
Let’s start with a basic Express app. If you don’t have one set up yet, you can create it by following these steps:
mkdir my-express-app && cd my-express-app
npm init -y
npm i express cors
mkdir my-express-app && cd my-express-app - creates the new project and move to the directory
npm init -y - initial the project with package.json file
npm i express cors - installs the required dependencies
Step 2: Create a simple Express App
Create an index.js file and set up a simple Express server.
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;
// Your custom CORS options will go here
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 3: Import and Configure CORS
Now, let’s add custom CORS options. To define the CORS middleware directly in Express app, use the example below by adding it to the index.js file.
const allowedOrigins = ['http://localhost:3000','https://example.com', 'https://another-domain.com'], // Allow only specific domains
const corsOptions = {
origin: (origin, callback) => {
//check if the request origin is present in the allowed origin list
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allow only specific HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'], // Specify allowed headers
};
// Apply CORS middleware
app.use(cors(corsOptions));
Step 4: Test Your CORS Configuration
Run you application using the below command:'
node index.js
To test your CORS settings, you can use tools like Postman or create a simple frontend application that makes requests to your Express API. If your requests are coming from the allowed origins list, they should work without any CORS errors.
To test with postman, pass custom origin header to the request in postman and test with different origins.
Summary
Configuring custom CORS options in an Express app is straightforward and essential for securing your API. By specifying which domains, methods, and headers are allowed, you can control access and enhance the security of your application.