Deploy Next.js Without Vercel: Self-Hosting Production Guide
Deploy a Next.js app without Vercel using standalone output, Docker, and a production-ready Node server that can run on any VM, container host, or cloud.
Deploy a Next.js app without Vercel using standalone output, Docker, and a production-ready Node server that can run on any VM, container host, or cloud.
Updated for Next.js 16 — which requires Node.js 20.9+, so the Docker images below are pinned to Node 24 LTS. Production deployments usually start with Vercel, then move toward providers such as Netlify or Firebase. They are convenient, but their cost and platform limits can become a problem.
A wrong serverless configuration can also lead to a large bill, like this story where a solo developer got a $100,000 Vercel bill after her app went viral.
So, what can we do?
The production deployment is not obvious from inspecting .next, but Next.js
can emit a standalone Node server. It runs without serverless functions or a
Vercel runtime.
This post packages that standalone output into a small Docker image.
If you are comparing production deployment patterns, the related Go Dockerfile optimization guide covers image-size tradeoffs, and the Next.js Electron Server Components guide shows where standalone server output matters outside a normal hosted web app.
npx create-next-app@latest nextjs-appnpm installnpm run buildFROM node:24-alpine
RUN npm install -g pnpm
COPY . .
RUN pnpm install
RUN pnpm run build
EXPOSE 3000
CMD ["pnpm", "run", "start"]This Dockerfile will build the Next.js app and install the dependencies in production mode, but its terrible for the performance and the size of the image will be huge.
docker build -t nextjs-app .Open the Docker Desktop and you should see the image there.
and as you see, its 1.53 GB, it's huge and absolutely terrible for the performance and it took like 3 minutes to build, and because it has no cache, every time you make a change, you have to rebuild the image.
docker run -p 3000:3000 nextjs-appYou will see the terminal output, and the app will be running on port 3000, it's typical nextjs output, but this time it's running directly on Node.js, without any serverless functions.
http://localhost:3000
and everything seems to be working fine, but we are not done yet.
FROM node:24-alpine AS base
# Install pnpm globally
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy all files to the working directory
COPY . .
# Install dependencies
RUN pnpm install
FROM base AS builder
# Build the application
RUN pnpm run build
FROM node:24-alpine AS runner
# Install pnpm in the runner stage
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy the necessary files from the builder stage
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/pnpm-lock.yaml ./pnpm-lock.yaml
# Install only production dependencies
RUN pnpm install --prod
EXPOSE 3000
# Start the application
CMD ["pnpm", "run", "start"]docker build -t nextjs-app .This time, it took around 1.5 minutes to build. And the image size is 1.36 GB, not much better if you ask me.
docker run -p 3000:3000 nextjs-apphttp://localhost:3000and everything seems to be working fine, but we are not done yet.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
};
export default nextConfig;FROM node:24-alpine AS base
# Install pnpm globally
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy all files to the working directory
COPY . .
# Install dependencies
RUN pnpm install
FROM base AS builder
# Build the application
RUN pnpm run build
FROM node:24-alpine AS runner
# Install pnpm in the runner stage
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy the necessary files from the builder stage for the standalone build
COPY --from=builder /app/.next/standalone ./
# Expose the port
EXPOSE 3000
# Start the application
CMD ["node", "server.js"]As you see, we are not copying the entire .next folder, and neither we are copying the node_modules folder, because we are using the dependencies from the base stage.
docker build -t nextjs-app .This time it took around 40 seconds to build, and the image size is just 287 MB, which is amazing if you compare it to the previous image.
docker run -p 3000:3000 nextjs-apphttp://localhost:3000
Doesn't this look amazing? cough cough WHERE ARE MY STYLES AND IMAGES?
Hey! don't give me that look, I know what I did, we are almost done. This is how the things are supposed to be, we are on the right path. Apparently the standalone build only contains the node_modules for the dependencies that are used in the app, and the css, images etc are not included in it.
Now it's time to fix it.
FROM node:24-alpine AS base
# Install pnpm globally
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy all files to the working directory
COPY . .
# Install dependencies
RUN pnpm install
FROM base AS builder
# Build the application
RUN pnpm run build
FROM node:24-alpine AS runner
# Install pnpm in the runner stage
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy the necessary files from the builder stage for the standalone build
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static .next/static
# Expose the port
EXPOSE 3000
# Start the application
CMD ["node", "server.js"]We added 2 lines, one to copy the static folder and the other to copy the public folder. The static folder contains the css, images, fonts etc, and the public folder contains the favicon, images, and other static assets.
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static .next/staticdocker build -t nextjs-app .Your image size will increase a bit according to how much assets you have, but it's still much better than the previous image.
docker run -p 3000:3000 nextjs-app
http://localhost:3000
And everything seems to be working fine, and the best part is that the image size is only 290 MB, and it's still running directly on Node.js, without any serverless functions.
Now you can just push this image to your favorite registry, and you are done.
Currently we are running it as root, which is not a good practice, so let's run it as a non-root user.
FROM node:24-alpine AS base
# Install pnpm globally
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy package.json and pnpm-lock.yaml to install dependencies first
COPY package.json pnpm-lock.yaml ./
# Install dependencies
RUN pnpm install
FROM base AS builder
# Copy the rest of the application files
COPY . .
# Build the application
RUN pnpm run build
FROM node:24-alpine AS runner
# Install pnpm in the runner stage
RUN npm install -g pnpm
# Set the working directory
WORKDIR /app
# Copy the necessary files from the builder stage for the standalone build
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static .next/static
# Change ownership of the files to the node user
RUN chown -R node:node /app
# Switch to the non-root user
USER node
# Add healthcheck for container monitoring
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
EXPOSE 3000
CMD ["node", "server.js"]// app/api/health/route.ts
export async function GET(request: Request) {
return new Response("OK");
}A health check serves both container orchestrators and load balancers. Docker can also use it to decide when the container is ready to receive traffic.
If you are running this in Github Actions, elsewhere, you can build the nextjs app in the github actions itself, and only do the final stage, and set it to copy from the local files like this.
name: Staging CI/CD
on:
push:
branches:
- main
jobs:
build-and-test-deploy:
name: Test, Build, Push
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v7
- uses: pnpm/action-setup@v6
with:
version: 12
- uses: actions/setup-node@v7
with:
node-version: 24
cache: "pnpm"
- name: Cache node_modules and Nextjs build files
uses: actions/cache@v6
with:
path: |
~/.npm
~/.cache
./node_modules
${{ github.workspace }}/.next/cache
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('**/pnpm-lock.yaml') }}-
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm build
- name: Build Docker Image
env:
IMAGE_TAG: ${{ github.sha }}
run: docker build -t nextjs-app .FROM node:24-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
# Copy the .next directory and other built artifacts to the container
COPY .next/standalone ./
COPY public ./public
COPY .next/static .next/static
# Add healthcheck for container monitoring
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1
USER node
EXPOSE 3000
# Start the Next.js app
CMD ["node", "server.js"]Generally it's safer to use the debian based image, because it's more compatible with various internal libraries.
On Vercel, the incremental cache — ISR pages, fetch caching, route handlers, image optimization — is shared and managed for you. A plain node server.js keeps its cache on the local disk of each instance instead: per-instance, ephemeral, and cold on every fresh container. But it's not all dark — we can point Next.js's cache at Redis and get similar behaviour on our own.
In Next.js 16 there are two related config options:
cacheHandler (singular) — the incremental cache backing ISR pages, route handlers and images. This is what we wire up below.cacheHandlers (plural) — the cache backends for the 'use cache' family (Cache Components), see the note at the end of this section.And since Next.js 15, you no longer need third-party adapters such as
@neshca/cache-handler — the handler interface is small enough to implement
directly. The code below is the official Redis cache handler
example,
which works with standalone output as-is.
redis client as a runtime dependencypnpm add redisimport type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
// The incremental cache handler, only used in production builds
cacheHandler:
process.env.NODE_ENV === "production"
? require.resolve("./cache-handler.js")
: undefined,
// Disable the default in-memory cache so Redis is the single shared
// source of truth across all instances.
cacheMaxMemorySize: 0,
};
export default nextConfig;const { createClient } = require("redis");
const { PHASE_PRODUCTION_BUILD } = require("next/constants");
// Prefix cache entries and tag indexes so they're easy to find (and flush)
// in Redis and don't collide with other keys.
const CACHE_PREFIX = "nextjs:cache:";
const TAG_PREFIX = "nextjs:tag:";
// App page/route entries carry their cache tags in this response header
// rather than in `ctx.tags` (which is only populated for fetch entries).
const NEXT_CACHE_TAGS_HEADER = "x-next-cache-tags";
// Cache entries aren't plain JSON: app page entries contain `Buffer`s
// (e.g. `rscData`) and a `Map` (`segmentData`). Plain `JSON.stringify` would
// turn a `Map` into `{}` and lose the buffer types, so we tag those values on
// the way out and rebuild them on the way back in.
function serialize(entry) {
return JSON.stringify(entry, (_key, value) => {
if (value instanceof Map) {
return { __type: "Map", value: Array.from(value.entries()) };
}
return value;
});
}
function deserialize(text) {
return JSON.parse(text, (_key, value) => {
if (value && value.__type === "Map") {
return new Map(value.value);
}
// `Buffer#toJSON()` produces `{ type: "Buffer", data: [...] }`.
if (value && value.type === "Buffer" && Array.isArray(value.data)) {
return Buffer.from(value.data);
}
return value;
});
}
module.exports = class CacheHandler {
constructor(options) {
this.options = options;
this.client = createClient({
url: process.env.REDIS_URL ?? "redis://localhost:6379",
});
// Redis won't work without error handling. Do not throw here, otherwise
// the client won't reconnect after a connection drop.
this.client.on("error", (error) => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.warn("Redis client error:", error);
}
});
// Connecting to Redis during `next build` can cause issues, so we only
// connect at runtime. `this.connection` resolves once the client is ready.
this.connection =
process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD
? Promise.resolve()
: this.client.connect().catch((error) => {
console.warn("Failed to connect to Redis:", error);
});
}
// Resolve a connected client, or `null` when Redis is unavailable so the
// app keeps working (without a shared cache) instead of crashing.
async getClient() {
await this.connection;
return this.client.isReady ? this.client : null;
}
async get(key) {
const client = await this.getClient();
if (!client) return null;
const entry = await client.get(CACHE_PREFIX + key);
return entry ? deserialize(entry) : null;
}
async set(key, data, ctx) {
const client = await this.getClient();
if (!client || !data) return;
// Collect tags from both sources: `ctx.tags` (fetch entries) and the
// `x-next-cache-tags` header (app page/route entries).
const headerTags = (data.headers?.[NEXT_CACHE_TAGS_HEADER] ?? "")
.split(",")
.filter(Boolean);
const tags = [...new Set([...(ctx?.tags ?? []), ...headerTags])];
// Let Redis auto-expire the entry when it carries a finite `expire`. Key
// the TTL on `expire`, never `revalidate`: past `revalidate` the entry is
// only stale (Next.js serves it while refreshing), so evicting it there
// would defeat that. ISR entries often omit `expire` entirely, in which
// case we set no TTL and rely on `revalidateTag` to invalidate.
const expire = ctx?.cacheControl?.expire;
const options = Number.isFinite(expire)
? { expiration: { type: "EX", value: Math.max(1, Math.ceil(expire)) } }
: {};
await client.set(
CACHE_PREFIX + key,
serialize({ value: data, lastModified: Date.now(), tags }),
options,
);
// Index this key under each of its tags so `revalidateTag` can find it.
await Promise.all(tags.map((tag) => client.sAdd(TAG_PREFIX + tag, key)));
}
async revalidateTag(tags) {
const client = await this.getClient();
if (!client) return;
// `tags` is either a single tag or an array of tags.
for (const tag of [tags].flat()) {
const tagKey = TAG_PREFIX + tag;
const keys = await client.sMembers(tagKey);
if (keys.length) {
await client.del(keys.map((key) => CACHE_PREFIX + key));
}
await client.del(tagKey);
}
}
// Used for an in-memory, per-request cache. Redis is the source of truth
// here, so there's nothing to reset between requests.
resetRequestCache() {}
};For local development you can run Redis with Docker: docker run -d -p 6379:6379 redis:8-alpine. Set REDIS_URL (defaults to redis://localhost:6379) in your host or container environment. Now, when you horizontally scale your app, the cache is shared across all the instances — a revalidateTag call on one container invalidates the entry for every other one too, because they all read from the same Redis.
When self-hosting your Next.js application, there are several key features you won't get compared to using Vercel:
Edge Functions and Global Distribution
Infrastructure Management
Development Experience
Performance Features
Yes, this setup fully supports Next.js's proxy layer! In Next.js 16,
middleware was renamed to proxy — a proxy.ts file exporting a proxy
function — and the standalone output mode supports it exactly the same way as
it does on Vercel. The old middleware.ts convention still works but is
deprecated, so new code should use proxy.ts. You can use it for:
One thing changed in Next.js 16: proxy always runs on the Node.js runtime
(edge is not supported for proxy). If you depend on edge runtime features,
keep using the deprecated middleware.ts for now.
The other difference is unchanged: the proxy runs on your own infrastructure rather than Vercel's edge network, so for global distribution you'll need your own CDN or a service like Cloudflare Workers.
The result is a standalone Next.js server in a small Docker image, with reusable build layers and a cache handler. It can run on Coolify, Docker, Kubernetes, or any host that can run a Node container.
sharp: Next.js uses it
automatically with next start or the standalone output mode.next dev and next build run on Turbopack
by default, so expect faster builds than the timings in the screenshots
above — output: "standalone" behaves the same.node:24-alpine / node:24-slim), and the CI workflow runs Node 24 with
pnpm 12.proxy (proxy.ts), see the Proxy section
above.@neshca/cache-handler adapter, which only supported Next.js up to 14.
Next.js 16's
Configuring Caching
documents the plain custom cacheHandler interface used above, plus
cacheMaxMemorySize: 0 and the newer cacheHandlers API for 'use cache'.
Discussion