[Next.js]: How to set up Express.js with Next.js

Next.js

05/11/2020


Install Express.js

BASH
npm i express

Creating server

/_server/server.js
JS
const next = require("next")
const dev = process.env.NODE_ENV !== "production"
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler()
const express = require("express")
// Router (Example)
const userRoutes = require("./routes/user")
nextApp.prepare().then(() => {
const app = express()
// Example: Register routes
app.use(userRoutes)
// Rendering page per request
app.get("*", (req, res) => {
return handle(req, res)
})
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`Listening on port ${port}...`)
})
})

package.json

Make the following changes to run the server.

/package.json
JSON
{
"scripts": {
"dev": "node _server/server.js",
"start": "node _server/server.js",
"build": "next build"
},
"dependencies": {
// ...
"express": "^4.17.1"
}
}

If you have nodemon you can configure like this:

/package.json
JSON
{
"scripts": {
"dev": "nodemon -w _server _server/server.js",
"start": "node _server/server.js",
"build": "next build"
},
"dependencies": {
// ...
"express": "^4.17.1"
}
}

You can install nodemon, if not previously installed with npm i -D nodemon

nodemon -w _server _server/server.js watches for the changes in _server directory and starts _server/server.js file

Extra: Add CORS header & Error Handler & Mongoose connection to server

Install Mongoose

BASH
npm i mongoose

Configure Mongoose URI

/_server/config.js
JS
module.exports = {
MONGODB_URI: `mongodb+srv://<DB_USERNAME>:<PASSWORD>@cluster0-xc4db.mongodb.net/test`,
}
/_server/config.js
JS
const express = require("express")
const next = require("next")
const dev = process.env.NODE_ENV !== "production"
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler()
const mongoose = require("mongoose")
const { MONGODB_URI } = require("./config")
// Router (Example)
const userRoutes = require("./routes/user")
nextApp.prepare().then(() => {
const app = express()
app.use(express.json())
// Set CORS header
app.use((req, res, next) => {
res.setHeader("Access-control-Allow-Origin", "*")
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, DELETE, PUT, OPTIONS"
)
// Allow client to set headers with Content-Type
res.setHeader("Access-Control-Allow-Headers", "Content-Type")
next()
})
// Example: Register routes
app.use(userRoutes)
// Rendering page per request
app.get("*", (req, res) => {
return handle(req, res)
})
// Error Handler
app.use((error, req, res, next) => {
const status = error.statusCode || 500
const message = error.message
const data = error.data // Passing original error data
res.status(status).json({ message: message, data: data })
})
// DB connection
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(result => {
const port = process.env.PORT || 3000
const server = app.listen(port, () => {
console.log(`Listening on port ${port}...`)
})
})
.catch(err => {
// Handle error
})
})

WRITTEN BY

Keeping a record