only allow requests from domain express

How to Only Allow Requests from Domain Express

If you want to restrict your server to only accept requests from a specific domain, you can achieve this by configuring your server to verify the "Origin" header of incoming requests.

Method 1: Using CORS Middleware

If you are using a Node.js-based framework like Express, you can use the built-in CORS middleware to set up this restriction. Here's an example:


const express = require('express');
const cors = require('cors');

const app = express();

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

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

app.use(cors(corsOptions));

// rest of your routes

In this example, we're specifying that the server should only allow requests from the domain "https://example.com". If any other domain tries to send a request, the server will respond with a 403 error.

Method 2: Implementing Your Own Middleware

If you prefer not to use the built-in CORS middleware, you can implement your own middleware function that checks the "Origin" header and rejects requests from unauthorized domains. Here's an example:


const express = require('express');

const app = express();

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

app.use((req, res, next) => {
  const { origin } = req.headers;
  if (allowedOrigins.indexOf(origin) !== -1) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    next();
  } else {
    res.status(403).send('Forbidden');
  }
});

// rest of your routes

In this example, we're checking the "Origin" header of incoming requests and sending a 403 error if the domain is not authorized. If the domain is authorized, we're setting the "Access-Control-Allow-Origin" header to the value of the incoming "Origin" header, which allows the request to proceed.

Both of these methods achieve the same result, so it's up to you to decide which one works best for your situation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe