0
0
Expressframework~5 mins

Configuring allowed origins in Express

Choose your learning style9 modes available
Introduction

Configuring allowed origins helps control which websites can talk to your server. It keeps your app safe by blocking unwanted access.

When you want only your website to access your API.
When you have multiple websites and want to allow some but not all to connect.
When you want to prevent other sites from making requests to your server.
When you are building a public API and want to limit usage to trusted domains.
Syntax
Express
const cors = require('cors');

const corsOptions = {
  origin: 'https://example.com',
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));

The origin option sets which website is allowed.

You can use a string for one origin or a function/array for multiple origins.

Examples
Allow only https://mywebsite.com to access your server.
Express
app.use(cors({ origin: 'https://mywebsite.com' }));
Allow multiple specific websites by checking the origin dynamically.
Express
const allowedOrigins = ['https://site1.com', 'https://site2.com'];

app.use(cors({
  origin: function(origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
}));
Allow all origins (not recommended for private APIs).
Express
app.use(cors());
Sample Program

This Express server allows requests only from https://trusted.com and https://partner.com. Others get blocked by CORS.

Express
import express from 'express';
import cors from 'cors';

const app = express();

const allowedOrigins = ['https://trusted.com', 'https://partner.com'];

const corsOptions = {
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
};

app.use(cors(corsOptions));

app.get('/', (req, res) => {
  res.send('Hello from server!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
OutputSuccess
Important Notes

Remember that CORS only affects browsers. Other clients like Postman are not blocked by CORS.

Always test your allowed origins carefully to avoid blocking your own app.

Summary

Configuring allowed origins controls which websites can access your server.

Use the cors middleware with the origin option to set allowed sites.

Test your settings to keep your app safe and working well.