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
You can use this conditional way of distinguishing between local development and production
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.
app.use
function for CORS is only executed if theNODE_ENV
environment variable is set todevelopment
.Install
dotenv
using npm:Create a
.env
file in the root directory of your project, and add the following line:Finally, require
dotenv
at the beginning of yourindex.js
file: