Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}...`);
});
like image 455
David Avatar asked Feb 02 '26 21:02

David


1 Answers

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();
like image 91
Mamun Avatar answered Feb 05 '26 10:02

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!