Recipes
Next.js
Serve a Next.js front end and a Kest API together.
Next.js builds the website (pages, React); Kest is the backend (data, rules, security). Together they are a complete product, and there are three common ways to connect them. Choose by how you deploy:
| A. Separate | B. Kest in front (proxy) | C. Static export | |
|---|---|---|---|
| Server-side rendering (SSR), middleware, ISR | yes | yes | no |
| Processes to run | 2 | 2 | 1 |
| One origin (no CORS, simple cookies) | no | yes | yes |
| Best for | development, teams deploying separately | production on one domain with SSR | marketing sites, dashboards, SPAs |
A. Separate servers (what you do in development)
Run next dev (port 3000) and your Kest app (port 8080). The browser talks to Next, and Next sends API calls onward. The easiest way is a Next rewrite, so the browser sees one address and CORS never comes up:
// next.config.js
module.exports = {
async rewrites() {
return [{ source: "/api/:path*", destination: "http://localhost:8080/api/:path*" }];
},
};// Kest: every route lives under /api
app.http(NettyHttpAdapter(8080)) { setGlobalPrefix("api") }If the browser must call Kest directly on another origin (a different domain), turn on CORS and say exactly who may call:
app.http(adapter) {
enableCors(CorsOptions(origins = listOf("https://app.example.com"), credentials = true)) // never "*" together with cookies
}and in the browser use fetch(url, { credentials: "include" }). Cookies across different sites also need SameSite=None; Secure, which is why one origin (B or C) is simpler.
B. One address: Kest in front of Next.js
In production put both behind one address. Kest answers its own routes; anything it does not know is forwarded to the Next.js server:
app.http(NettyHttpAdapter(8080)) {
setGlobalPrefix("api") // Kest's own routes: /api/...
useReverseProxy("http://next:3000") // every other path goes to Next.js
}What the proxy does:
- Kest routes always win. Only a request that would be a
404is forwarded;/docs,/metrics,/healthand your controllers stay Kest's. /api/...is never forwarded (theexceptparameter, default["/api"]): a mistyped API path gives Kest's JSON 404, not the front end's HTML page.- Method, path, query string, headers and body are forwarded; hop-by-hop headers are dropped;
X-Forwarded-For,-Hostand-Protoare added so Next knows the real address. - Redirects and cookies pass through untouched (each
Set-Cookiestays separate). - A dead Next server is a 502, a slow one a 504 (
timeout, default 30 s).
Run them with docker compose:
services:
kest: { image: shop/kest-api, ports: ["80:8080"], environment: { NEXT_URL: "http://next:3000" }, depends_on: [next] }
next: { image: shop/next-app, expose: ["3000"] } # not published: only Kest talks to itLimits: the body is buffered (no streaming of huge responses), and WebSockets are not proxied, so Next's hot-reload in next dev will not work through the proxy: use A in development and B in production.
C. Static export: one process, no Node in production
If your Next.js site has no server-side rendering, build it to plain files and let Kest serve them:
// next.config.js
module.exports = { output: "export", trailingSlash: true }; // next build -> ./outapp.http(NettyHttpAdapter(8080)) {
setGlobalPrefix("api")
serveStatic("/", "out", index = "index.html", maxAgeSeconds = 3600) // the built site at /
}Files are served with an ETag and cache headers; a folder request returns its index.html (so /about serves out/about/index.html); unknown paths are a 404, and your API routes keep working. Static files are checked before routing but only answer paths that exist. Give _next/static/* a long cache (it has hashed names): put a CDN or reverse proxy in front.
Authentication: keep tokens out of JavaScript
The safest pattern for a browser app is a cookie the browser cannot read from JavaScript (HttpOnly), set by Kest:
@Post("/login") fun login(@Body creds: Login, @Response(passthrough = true) res: RawResponse): User { // jwt is the JwtService
val user = auth.check(creds)
res.cookie(ResponseCookie("session", jwt.sign(mapOf("sub" to user.id)), maxAge = Duration.ofHours(1), secure = true, httpOnly = true, sameSite = "Lax"))
return user
}With one origin (B or C) the cookie is sent automatically on every call, and a script injected into the page (XSS) cannot steal it. Add CSRF protection when you use cookies for state-changing requests.
Server Components and route handlers run on the Next.js server, so they call Kest server to server and must forward the user's cookie themselves:
// app/orders/page.tsx (a Server Component)
import { cookies } from "next/headers";
export default async function Orders() {
const res = await fetch(`${process.env.KEST_URL}/api/orders`, {
headers: { cookie: (await cookies()).toString() }, // pass the browser's session on to Kest
cache: "no-store", // user data must not be cached across users
});
const orders = await res.json();
return <ul>{orders.map((o: any) => <li key={o.id}>{o.total}</li>)}</ul>;
}(In Next.js 15 and later cookies() is asynchronous, as shown. Check the Next.js documentation for your version: the details change between releases.)
A typed client from your OpenAPI document
Kest publishes GET /docs/openapi.json (OpenAPI). Generate TypeScript types from it so the front end and the API cannot drift apart:
npx openapi-typescript http://localhost:8080/docs/openapi.json -o src/api-types.tsimport type { paths } from "./api-types";
type Order = paths["/api/orders/{id}"]["get"]["responses"]["200"]["content"]["application/json"];Re-run it in CI and the build fails when a field the front end uses disappears.
Common problems
| Symptom | Cause and fix |
|---|---|
| Browser: "blocked by CORS policy" | the browser calls another origin: use a Next rewrite (A) or one address (B, C), or enableCors with exact origins |
| Cookie is set but not sent | different sites need SameSite=None; Secure and credentials: "include"; same origin avoids all of it |
| Next shows the wrong host in links | forward the original Host: the proxy sets X-Forwarded-Host; configure Next to trust it |
/api/typo shows an HTML page | it is not forwarded: check except includes your API prefix |
| Hot reload does not work through Kest | WebSockets are not proxied: develop with A |
| Static export: a page shows 404 | enable trailingSlash: true, and use only features available in a static export (no server components that read request data) |
| Pages are slow behind the proxy | enable useCompression() on Kest once (not in both), and cache static assets at a CDN |
Verified
The proxy was tested against a fake upstream server (path, query, headers, body, status, redirects, cookies, the /api exception and a dead upstream) and the static export against a built directory layout. It was not run against an actual next start process in this repository, so do a first run of your own build.