Blog>
Snippets

Using Dynamic Routes with Custom Server

Provide an example of a custom server setup that handles incoming requests and maps them to the appropriate dynamic routes in a Next.js application.
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();

  // Dynamic route for a user with a specific id
  server.get('/user/:id', (req, res) => {
    const actualPage = '/user';
    const queryParams = { id: req.params.id };
    app.render(req, res, actualPage, queryParams);
  });

  // Handling all other requests with the default Next.js handler
  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});
This code snippet creates a custom server using Express and Next.js. It first initializes the Next.js app and creates a request handler. Then it prepares the server to handle a dynamic route for a user profile page, where the user's id is a path parameter. All other requests that don't match the specific dynamic route are handled by Next.js's default handler. Finally, the server listens on port 3000.