...

/

Using a Custom Express.js Server

Using a Custom Express.js Server

Learn to customize any Express.js server for our application.

Writing a custom Express.js server to render Next.js pages is easier than we might think.

Let’s start with an index.js file inside the project root and import the required dependencies:

Press + to interact
const { parse } = require('url');
const express = require('express');
const next = require('next');

We now need to instantiate the Next.js app, and we can do that by adding the following code right after the import statements:

Press + to interact
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

Universal URL handling

Let’s complete our server by writing the main function, which takes every incoming GET request and passes it to Next.js for server-side rendering:

Press + to interact
async function main() {
try {
await app.prepare();
const handle = app.getRequestHandler();
const server = express();
server.get('*', (req, res) => {
const url = parse(req.url, true);
handle(req, res, url);
}).listen(3000, () => console.log('server ready'));
} catch (err) {
console.log(err.stack);
}
}
main();

Let’s focus on the main function body and see what’s going on. First of all, we wait for the Next.js app to be ready for rendering. Then, we instantiate a ...