skip to Main Content

How to use conditional cors in node js to run in local.

I am using node js app. Now whenever I need to run in local I have to uncomment lines 11 to 15 and while committing code I am commenting on those lines.

Is there any way I can use some conditions to avoid that bad practice?

const express = require("express");
const cors = require("cors");
const app = express();

app.use(express.json());

// to run in local
/* app.use(
  cors({
    origin: "http://localhost:3000/",
  })
); */

app.get("/api/hello", (_req, res, next) => {
    res.send("hello");
});

app.use((err, req, res, next) => {
  // some operation 
});


const port =  8000;
app.listen(port, () => {
  logger.info(`Server running on ${port}...`);
});

2

Answers


  1. You can use this conditional way of distinguishing between local development and production

    const express = require("express");
    const cors = require("cors");
    const app = express();
    
    app.use(express.json());
    
    // to run in local
    if (process.env.NODE_ENV === "development") {
      app.use(
        cors({
          origin: "http://localhost:3000/",
        })
      );
    }
    
    app.get("/api/hello", (_req, res, next) => {
      res.send("hello");
    });
    
    app.use((err, req, res, next) => {
      // some operation
    });
    
    const port = 8000;
    app.listen(port, () => {
      logger.info(`Server running on ${port}...`);
    });
    
    
    Login or Signup to reply.
  2. You can use a conditional statement to enable CORS based on the environment.
    To achieve that you can set an environment variable that specifies whether the app is running in production or development mode.

    if (process.env.NODE_ENV === 'development') {
      app.use(
        cors({
          origin: "http://localhost:3000",
        })
      );
    }
    

    app.use function for CORS is only executed if the NODE_ENV environment variable is set to development.

    Install dotenv using npm:

    npm install dotenv
    

    Create a .env file in the root directory of your project, and add the following line:

    NODE_ENV=development
    

    Finally, require dotenv at the beginning of your index.js file:

    require('dotenv').config();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search