How I set up MERN stack Node.js backends. Heavily inspired by projects made by Brad Traversy.
Dependencies
- express : JS web server framework
- dotenv : read environment variables/config
- helmet : protect app
Server setup
const express = require('express')
const dotenv = require('dotenv')
const helmet = require('helmet')
const xss = require('xss-clean')
const route1 = require('./routes/route1')
const route2 = require('./routes/route2')
dotenv.config({ path: './config/config.env' })
connectDB()
const app = express()
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'))
}
app.use(express.json())
app.use(helmet())
app.use(xss())
app.use(cors())
app.use('/api/v1/route1', myroute1)
app.use('/api/v1/route2', myroute2)
const PORT = process.env.PORT || 5000
const server = app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode`))
process.on('unhandledRejection', (err, promise) => {
console.log(`Error: ${err.message}`)
server.close(() => process.exit(1))
})