Next.jsMedium

How do you configure custom server in Next.js?

A custom server is your own Node.js HTTP server (plain http, Express, Fastify) that creates a Next.js app with next({ dev }), calls app.prepare(), and forwards requests to app.getRequestHandler(). Use it only when you need something Next.js cannot do, like attaching WebSockets to the same port, because it gives up some optimizations and platform support.

Setup

  1. Create server.ts that imports next and node:http.
  2. const app = next({ dev, hostname, port }), then await app.prepare().
  3. Handle your special routes first; pass everything else to handle(req, res).
  4. Change scripts: "dev": "tsx server.ts", "start": "NODE_ENV=production node dist/server.js".

Trade-offs

  • Cannot be deployed to Vercel and many serverless platforms.
  • output: "standalone" does not trace your custom server file; you must make sure its dependencies are available.
  • You own process management, graceful shutdown, logging and HTTP hardening.
  • Code in server.ts is not compiled by Next.js; compile it with tsc or run it with tsx.

Usually you do not need one

  • Redirects, rewrites and headers: next.config.ts or proxy.ts.
  • APIs and webhooks: Route Handlers.
  • Background work after responses: after().
  • Startup code, tracing and monitoring: instrumentation.ts (register() runs once when the server starts).
  • Real-time features: a separate WebSocket service, or a managed service (Pusher, Ably, Liveblocks, Supabase Realtime).

When it is reasonable

Legacy Express apps adopting Next.js gradually, WebSockets on the same port, or unusual networking requirements on your own servers.

Code example

tsx
1// server.ts
2import { createServer } from "node:http";
3import next from "next";
4import { WebSocketServer } from "ws";
5
6const dev = process.env.NODE_ENV !== "production";
7const port = Number(process.env.PORT ?? 3000);
8const app = next({ dev, hostname: "0.0.0.0", port });
9const handle = app.getRequestHandler();
10
11await app.prepare();
12
13const server = createServer((req, res) => {
14 if (req.url === "/healthz") {
15 res.writeHead(200).end("ok");
16 return;
17 }
18 handle(req, res); // everything else goes to Next.js
19});
20
21// The usual reason for a custom server: WebSockets on the same port
22const wss = new WebSocketServer({ noServer: true });
23server.on("upgrade", (req, socket, head) => {
24 if (req.url === "/ws") wss.handleUpgrade(req, socket, head, (ws) => ws.send("hello"));
25});
26
27server.listen(port, () => console.log(`> Ready on http://localhost:${port}`));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app