Skip to content

Instantly share code, notes, and snippets.

@arifvn
Last active November 21, 2021 04:05
Show Gist options
  • Save arifvn/7d1f434e2f3ffb3a81f78517852cf4c6 to your computer and use it in GitHub Desktop.
Save arifvn/7d1f434e2f3ffb3a81f78517852cf4c6 to your computer and use it in GitHub Desktop.
Sample nodejs server
require("colors");
const express = require("express");
const logger = require("morgan");
const helmet = require("helmet");
const xss = require("xss-clean");
const hpp = require("hpp");
const mongoSanitize = require("express-mongo-sanitize");
const rateLimit = require("express-rate-limit");
const cors = require("cors");
const morgan = require("morgan");
const { PORT, NODE_ENV } = require("./src/config/config");
const connectToDb = require("./src/config/db");
const auth = require("./src/routes/auth.route");
const users = require("./src/routes/users.route");
const errorHandler = require("./src/middlewares/errorHandler");
// middlewares
const app = express();
app.use(express.json());
app.use(helmet());
app.use(mongoSanitize());
app.use(xss());
app.use(hpp());
app.use(cors());
app.use(logger("dev"));
const ratelimitoptions = {
windowms: 11 * 60 * 1000,
limit: 100,
handler: (_req, res, _next, options) => {
res
.status(options.statuscode)
.send({ success: false, error: options.message });
},
};
app.use(rateLimit(ratelimitoptions));
// routes
app.use("/api/v1/auth", auth);
app.use("/api/v1/users", users);
app.use(errorHandler);
const main = () => {
connectToDb();
const server = app.listen(PORT || 5000, () =>
console.log(
`server listening in ${NODE_ENV} on port ${PORT || 5000}`.green.bold
)
);
process.on("unhandledrejection", (err) => {
console.log(`error : ${err.message}`.red.bold);
server.close(() => process.exit(1));
});
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment