Home > OS >  How to white list sub domains in Node js
How to white list sub domains in Node js

Time:01-11

I'm using the below regex to white-list the domains, but the below code xxx.sampledomain.com is not working

  let url = req.headers.origin.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0]
  let client = CLIENTS.filter(client => client.websiteAddress.replace('www.', '') === url)[0];

Please guide

CodePudding user response:

I am adding a code . It will check. allow to that subdomain or not

// List of allowed subdomains
const allowedSubdomains = ["subdomain1", "subdomain2", "subdomain3"];

const subdomainRegex = new RegExp(`^(?:https?:\/\/)?(?:www\.)?(${allowedSubdomains.join("|")})\.`);

// Function to check if a subdomain is allowed
function isAllowedSubdomain(subdomain) {
  return subdomainRegex.test(subdomain);
}

For example:

let subdomain = req.headers.origin.match(subdomainRegex)[1];

// Extract the subdomain from the origin

if (isAllowedSubdomain(subdomain)) {
  console.log("Allow this subdomain")
} else {
  console.log("This subdomain is not allowed")
}

If you have any question, You can ask

CodePudding user response:

You can use cors, a npm lib that can help you achieve the same functionality.

var express = require('express')
var cors = require('cors')
var app = express()
 
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
 
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
 
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
  • Related