Skip to content
cd ~/blog: all posts

12 min read

A Next.js starter kit for Laravel, Django or FastAPI backends

Why I built an open-source Next.js 16 starter for frontends that talk to a REST API: what is in it, how the code is laid out, how the API layer and token refresh work, and the rules it follows.

  • Next.js
  • TypeScript
  • Open source
  • Auth

Most of my projects have the same shape: a backend in Laravel, NestJS or FastAPI, and a Next.js frontend that talks to it over REST. Every new project began with the same week of plumbing: an API client, login, token refresh, protected routes, error messages on forms, linting, tests and CI.

So I turned that week into a starter kit and put it on GitHub. It is MIT-licensed, and this site is built on it.

mdalarmansorker/nextjs-typescript-starter-kitThe source code, setup guide and docs on GitHub. (opens in a new tab)

Who it is for

Teams whose API lives somewhere else, whatever it is built with: Laravel, Django, FastAPI, Express, Rails, Go or anything that speaks JSON over HTTP. There is no database or ORM in it on purpose. The backend owns the data; the Next.js app is the interface in front of it.

What is in it

  • Next.js 16 with the App Router, React 19 and TypeScript in strict mode.
  • A server-only API layer: one function for every request, with timeouts, query parameters, pagination, uploads and downloads, typed errors and runtime response checks with zod.
  • Error messages and field errors read from the common backend formats (Laravel, Django REST Framework, FastAPI, Express, RFC 9457, JSON:API) in one function you can adapt.
  • Login, logout and protected routes: httpOnly token cookies, token refresh with rotating refresh tokens, token revocation on logout, and a return to the same page after logging in again.
  • An environment check at startup, so a missing API_URL stops the server with a clear message instead of failing on the first request.
  • AES-256-GCM encryption with purpose labels, expiry and key rotation.
  • Redux Toolkit with typed hooks and a store per request, and Tailwind CSS 4.
  • Vitest and React Testing Library for unit and component tests, Playwright for end-to-end tests.
  • ESLint, Prettier, Stylelint, a pre-commit hook and GitHub Actions CI.
  • Security headers, error and 404 pages, robots.txt, a sitemap and a social preview image.

How the code is laid out

Every kind of code has one place to live, so you never wonder where a new file goes and a reviewer never has to hunt for one. Routes stay thin, the UI lives in views, and everything that talks to the backend sits behind a server-only wall.

text
app/              routes only; each page.tsx stays thin and renders a viewviews/<feature>/  the UI of a pagecomponents/       shared pieces: form fields, paginationservices/api/     server-only API layer: handleRequest and one service class per resourceservices/app/     cookies (CookieService) and the login sessionconstants/        endpoint paths, cookie names, protected routeslib/              Redux store, typed hooks, slices and cn()utils/            framework-free helpers; *.server.ts files are server-onlytypes/            shared types, re-exported from types/index.tsproxy.ts          route protection (Next.js 16 replaced middleware.ts with proxy.ts)docs/             one guide per area: API layer, auth, testing, security, SEO …e2e/              Playwright tests and the mock API they run againstscripts/          the make:module and make:type code generators

Unit tests sit next to the code they test (thing.ts and thing.test.ts), and every import uses the @/ alias, so moving a file never means counting ../ segments.

Starting a project

bash
git clone https://github.com/mdalarmansorker/nextjs-typescript-starter-kit.git my-appcd my-appnpm install                  # also installs the pre-commit hookcp .env.example .env.local   # then set API_URLnpm run dev

Then connect your API in three places: the endpoint paths in constants/api/auth.api.ts, the login response (TokenResponseSchema already accepts token, access_token, access and the usual refresh-token and expiry fields), and readApiError, only if your API sends errors in an unusual shape.

Adding a feature

bash
npm run make:module invoice

That one command creates the page, the view, a server-only service with index, show, store, update and destroy, the type and the endpoint constant, and formats them to match the rest of the code. It refuses to overwrite anything that already exists.

For a complete example, the kit ships a projects module: a paginated list, create and edit forms with validation errors from both the browser and the API, delete, and a 404 for unknown ids, with unit and end-to-end tests against a mock API.

The API layer

In most frontends I have inherited, fetch calls are spread across components and hooks, each handling errors its own way. Some forget the token, most forget the timeout, and none of them check what the API actually sent back. In the kit there is one function for all of it: handleRequest, in services/api/base.service.ts. It imports server-only, so the build fails if a client component ever imports it, and the API URL and tokens stay on the server.

One service per resource

Each resource gets a small service class with one method per endpoint. The methods only describe the request; handleRequest does the rest.

ts
export default class ProjectService {  static index = ({ page = 1 } = {}) =>    handleRequest(PROJECTS, {      requiresAuth: true,      query: { page, per_page: PROJECTS_PER_PAGE },      parse: parsePage(ProjectSchema, { page, perPage: PROJECTS_PER_PAGE }),    });   static show = (id: string) =>    handleRequest(`${PROJECTS}/${encodeURIComponent(id)}`, {      requiresAuth: true,      parse: parseProject,    });}

Query parameters go in the query option instead of being glued onto the URL, and ids from the user are encoded before they go into a path. Pages read through the service in a Server Component; forms write through it in a server action.

Check what the API sent

TypeScript types disappear when the code runs. If the backend renames a field, the type still compiles and the page shows undefined somewhere far from the cause. So every service passes a zod schema as parse.

ts
const ProjectSchema = z.object({  // Some APIs send numeric ids; the app treats every id as a string.  id: z.union([z.string(), z.number()]).transform(String),  name: z.string(),  description: z.string().nullish().transform(value => value ?? null),});

When a response does not match, handleRequest logs the details on the server and throws an ApiError with status 502 and a plain message. The user sees an error page, and the log says exactly which field was wrong.

One place to read errors

Backends disagree on what an error looks like. Instead of a parser per project, readApiError in services/api/api-errors.ts accepts the common shapes:

  • { message, errors } from Laravel, NestJS and many custom APIs.
  • { error: 'text' } from Express, Rails and Go APIs.
  • { error: { message, details } } from Google-style JSON APIs.
  • { detail } from Django REST Framework, and FastAPI, which puts validation errors in detail as a list.
  • { title, detail, errors } from RFC 9457 problem details and ASP.NET.

Field errors are turned into one shape, { field: ['message'] }, whether they arrived as Laravel's object of lists, FastAPI's loc paths, zod or Joi paths, express-validator's param or JSON:API pointers. If your API is different, you change this one function and every form follows.

Errors in forms

A server action validates the form with zod first, then calls the service. What it does with an ApiError depends on the status:

ts
try {  await ProjectService.store(parsed.data);} catch (error) {  // The API's own validation goes back to the form.  if (error instanceof ApiError && error.status < 500 && error.status !== 404) {    return { values, message: error.message, fieldErrors: error.fieldErrors };  }   // 404 and 5xx go to the not-found and error pages.  throw error;} // Outside the try: redirect() works by throwing.redirect('/projects');

A 4xx is returned to a useActionState form, so "The name has already been taken." appears under the right field and the form keeps what the user typed. A 5xx is thrown, and in production Next.js hides its message from the browser.

For a request with requiresAuth, a 401 never reaches the page: handleRequest refreshes the token and retries once. If the API refuses again, it ends the session and sends the user to login with the page to come back to. How that works without logging anyone out by accident is the next section.

Login and token refresh

Token refresh looks simple: when the access token expires, send the refresh token and get a new pair. It stops being simple the first time a page makes three API calls at once with an expired token, and the user is logged out for no visible reason. This is how the kit handles it.

Tokens stay on the server

After login, the server action stores the tokens with saveSession in httpOnly cookies. Browser JavaScript cannot read them, so a script injected into the page cannot steal them. Only the server reads the cookies, and it attaches the token when it calls the API.

Three places a token can expire

In the App Router, the code that notices an expired token runs in three different places, and cookies can only be written in two of them:

  • On a page load. proxy.ts runs first: if the access-token cookie is gone but the refresh token is still there, it sends the request through a refresh route that stores new tokens and comes straight back.
  • While a Server Component renders. Cookies are read-only there, so handleRequest redirects to the same refresh route, which refreshes and returns to the page.
  • In a server action or route handler. Cookies can be written, so handleRequest refreshes in place and retries the request once.
ts
// proxy.ts: only page loads. Server actions (POST) refresh inside handleRequest.if (!hasAccessToken && hasRefreshToken && request.method === 'GET') {  const refreshUrl = new URL(REFRESH_ROUTE, request.url);  const encoded = encodeRedirectPath(pathname + search);   if (encoded) refreshUrl.searchParams.set('redirect', encoded);   return NextResponse.redirect(refreshUrl);}

Rotation and the race

Many APIs rotate refresh tokens: each one works once, and using it a second time counts as theft and revokes the session. That is good security, and it is exactly what breaks naive refresh code. Three parallel requests see the expired token, all three try to refresh with the same refresh token, the first wins, and the other two are treated as reuse. The user is logged out.

So calls that arrive together with the same refresh token share one request to the API:

ts
export const refreshTokens = (refreshToken: string): Promise<Session> => {  const existing = recentRefreshes.get(refreshToken);   if (existing) return existing.result;   const result = sendRefresh(refreshToken);   recentRefreshes.set(refreshToken, { result, startedAt: Date.now() });  // A failure isn't reused: the next request may try again.  result.catch(() => recentRefreshes.delete(refreshToken));   return result;};

The result is reused for ten seconds, which covers parallel requests and several open tabs. The sharing is per server process, so with several instances behind a load balancer the API should allow a short grace period for the previous refresh token.

Back to the same page

When a session does end, the user should not lose their place. proxy.ts passes the current path to server code in an x-current-path header, and always overwrites it so a browser cannot supply its own. The login page gets it as ?redirect=, and every redirect target from a URL or a form has to pass isSafeRedirectPath, so the parameter cannot be used to send someone to another site.

What the proxy does not do

The proxy only checks that a token cookie exists. It does not decide whether the token is valid or what the user may see; only the API knows that. A protected route in the frontend is a convenience for the user. The API still has to authorize every request.

The rules it follows

A folder layout only helps if everyone follows it, so the kit writes its rules down. They live in AGENTS.md (CLAUDE.md points at it), which means AI coding agents read and follow the same rules as the people on the team.

API calls

  • Every backend call goes through one function, handleRequest. Nothing calls fetch on the API directly.
  • The API layer imports server-only, so the API URL and tokens never reach the browser, and no client component may import it.
  • Read data in Server Components, change data in server actions. Server actions are never used for reads.
  • Check responses at runtime with a zod schema: a TypeScript type is a promise the API never signed.
  • Pass query parameters with the query option instead of building query strings, and encode user input in paths with encodeURIComponent.
  • Server actions catch ApiError and return the message and field errors for 4xx responses, so forms can show them; 5xx errors are rethrown or logged.
  • API error bodies are read in one place, readApiError, so adapting to a new backend means changing one function.
  • redirect() and notFound() work by throwing, so they are called outside try blocks.

Auth and security

  • Protected sections are listed in one place, PROTECTED_ROUTES. The proxy only checks that a token cookie exists; the API must still authorize every request.
  • Tokens are stored with saveSession, in httpOnly cookies, and every auth cookie is listed in COOKIE_NAMES so logout deletes it.
  • Redirect targets that come from URLs or forms must pass isSafeRedirectPath, which closes open redirects.
  • API_URL, tokens and the encryption key never reach the browser. Only NEXT_PUBLIC_ variables do.
  • A new environment variable is added to .env.example, the startup check and its guide in the same change.

Code style

  • TypeScript in strict mode with noUncheckedIndexedAccess: reading an array or record item may give undefined, and the code has to handle it.
  • Prettier formats, ESLint sorts the imports. Nobody formats or orders imports by hand.
  • Components and views are PascalCase files; everything else follows its neighbours.
  • Follow the patterns in nearby files before adding a new abstraction or dependency.

Tests

  • Tests query the page the way a person uses it: by role and label, not by class name or test ID.
  • Mock the layer below: test a server action by mocking its service, and a service by mocking handleRequest.
  • End-to-end tests run against the production build and a mock API, so they need no real backend.
  • Coverage thresholds are never lowered to make a run pass.

Docs and Git

  • Every change that affects behavior, setup or conventions updates its guide in docs/ and adds a line to the changelog in the same pull request.
  • Commits follow Conventional Commits: feat:, fix:, docs:, test:, refactor:, chore:.
  • A pre-commit hook runs ESLint, Prettier and Stylelint on staged files, and it is never skipped.
  • Before a change is called done: lint, format check, typecheck and the unit tests; plus the build and end-to-end tests when it touches pages, routing, auth or the API layer.

Every part above has a guide in the docs/ folder and tests for its edge cases. If you build something with the kit, I would like to hear about it, and issues and pull requests are welcome.

Star, fork or open an issue on GitHubgithub.com/mdalarmansorker/nextjs-typescript-starter-kit (opens in a new tab)