Blog>
Snippets

Setting Up a Custom Express Server for Next.js 14

Demonstrate how to use a custom Express server with the Next.js 14 app to handle server-side logic before deploying.
const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  // Custom route example
  server.get('/p/:id', (req, res) => {
    const actualPage = '/post';
    const queryParams = { id: req.params.id };
    app.render(req, res, actualPage, queryParams);
  });

  // Default request handler
  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, err => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});
This script sets up an Express server for a Next.js app. After importing the required modules and initializing a Next.js app, it prepares the app and then creates an Express server. The server defines a custom route '/p/:id' that maps to a Next.js page '/post'. The server also sets up a default route handler to manage all other requests with Next.js routing. Finally, it starts listening on port 3000.