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}...`);
});
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With