Repository navigation
Can I self-host Next.js with a custom HTTP or Express server and keep hot reloading? #99762
SummaryI like the developer experience provided by Next.js on Vercel, but I want control over the underlying server so I can manage WebSocket connections, CRON jobs, Redis, Queues, etc. Can I run Next.js through my own Node.js HTTP or Express server while retaining Fast Refresh and hot reloading during development? Additional informationNo response ExampleNo response |
Replies: 2 comments
|
Yes, Next.js has a server API for exactly this kind of setup. I’ve used it with a self-hosted Docker Compose stack on AWS, and I have full hot-reloading for both NextJS and Server code in development. The essential server setup is very small: import http from "http";
import next from "next";
const port = Number(process.env.APPLICATION_PORT);
const dev = process.env.NODE_ENV !== "production";
// Enables Next.js development mode, including Fast Refresh.
const app = next({ dev, port });
await app.prepare();
const handle = app.getRequestHandler();
http.createServer((req, res) => {
handle(req, res);
}).listen(port);The key line is: const app = next({ dev, port });When And in development I also run the custom server through {
"scripts": {
...,
"dev:server": "tsx watch src/server.ts",
...,
}
}These two are complementary in development.
This means both sides of the application remain convenient to develop: UI and Next.js changes refresh through Next.js, while changes to WebSockets, cron jobs, Redis integration, queues, health checks, or other server-level code cause an automatic server restart. When running inside Docker, the source directory must also be bind-mounted into the container so both watchers can see local file changes. Here's the official Next.js Custom Server documentation: |
Yes, Next.js has a server API for exactly this kind of setup. I’ve used it with a self-hosted Docker Compose stack on AWS, and I have full hot-reloading for both NextJS and Server code in development.
The essential server setup is very small:
The key line is:
When
devistrue, Nex…