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
- Create
server.tsthat importsnextandnode:http. const app = next({ dev, hostname, port }), thenawait app.prepare().- Handle your special routes first; pass everything else to
handle(req, res). - 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.tsis not compiled by Next.js; compile it withtscor run it withtsx.
Usually you do not need one
- Redirects, rewrites and headers:
next.config.tsorproxy.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.ts2import { createServer } from "node:http";3import next from "next";4import { WebSocketServer } from "ws";56const 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();1011await app.prepare();1213const 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.js19});2021// The usual reason for a custom server: WebSockets on the same port22const 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});2627server.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.