Skip to content
Yusuf Bagus Anggara
All posts

Next.js + Laravel: REST & GraphQL Integration Patterns

Practical patterns for wiring Next.js frontends to Laravel APIs — REST and GraphQL, and how to choose between them.

OCT 20, 2026 · 5 MIN READ · NEXT.JS, LARAVEL, ARCHITECTURE

Two frontends, two contracts, one backend stack

Most of my production work lives in one configuration: a Next.js frontend talking to a Laravel API. Over the years I've shipped it with REST (jamtangan.com) and with GraphQL (voila.id). Both worked. Both taught me different things about where the contract between frontend and backend should live.

This isn't a REST-vs-GraphQL verdict piece. It's the set of patterns I keep reusing, and the trade-offs I actually weigh when a project starts.

The REST patterns that survived every project

One fetch wrapper, no exceptions

The first thing I set up on any Next.js project is a single fetch wrapper. Every request goes through it — no fetch() calls scattered through components. It's where base URL, the auth header, error normalization, and the rest of the headers live:

export class ApiError extends Error {
  constructor(public status: number, message: string) {
    super(message)
  }
}

// getToken() reads the bearer token from wherever you decided it lives.
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${process.env.API_BASE_URL}${path}`, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${getToken()}`,
      ...init?.headers,
    },
    ...init,
  })

  if (!res.ok) {
    const body = await res.json().catch(() => null)
    throw new ApiError(res.status, body?.message ?? res.statusText)
  }

  return res.json() as Promise<T>
}

Two details worth defending here. First, the token is attached in exactly one place — a component never reads, stores, or forwards it, so rotating where the token lives means editing one function. Second, error normalization: components should catch one ApiError type, not interpret every backend response shape.

Auth: token or session, choose consciously

Laravel gives you both — bearer tokens via Sanctum, or cookie sessions. The projects I've shipped took different answers, and both are defensible: jamtangan.com authenticates its REST API with bearer tokens, while voila.id rides on a session cookie.

The mistake isn't picking the wrong one. It's picking one by default. Tokens push storage, expiry, and revocation concerns onto you — but they don't care who sends them: browser, mobile client, or a server-to-server call. Sessions keep CSRF and cookie handling in Laravel's wheelhouse and need almost no client code, but they tie the API to browser-originated requests. Decide based on who consumes the API, then write the decision down.

Shape errors so the UI can react

A 500 with an HTML error page is useless to a React component. Every Laravel API I maintain returns a consistent error envelope — status, machine-readable code, human message — and the frontend maps that to user-facing states: retryable vs. fatal, validation vs. server error. Empty, loading, and error states are part of the contract, not an afterthought.

The GraphQL patterns that made voila.id work

Schema as the living contract

With GraphQL, the schema does the heavy lifting that types do in REST. The frontend gets a typed client from the schema, and breaking changes surface at codegen time instead of at 2 a.m. in production:

query CatalogPage($filters: ProductFilterInput) {
  products(filters: $filters) {
    edges {
      node {
        id
        name
        slug
        price { amount currency }
        thumbnail { url width height }
      }
    }
    pageInfo { hasNextPage endCursor }
  }
}

When the backend renames price to finalPrice, the frontend build breaks before the deploy does. That's the entire value proposition, and it only holds because codegen keeps the client's types in sync with the schema.

Keep server cache and UI state in separate lanes

Apollo's cache and my client state store (Zustand, in both projects) can quietly become entangled — UI state leaking into the normalized cache, or cached server data re-implemented as local state. The rule I settled on: Apollo owns anything the server truthfully knows. Zustand owns anything the server doesn't — cart drafts, filter UI state, wizard progress. A piece of state lives in exactly one of the two.

Pagination and nested reads are the real win

GraphQL earns its complexity on catalog pages: one query fetches the product grid, its facets, and its pagination metadata. Under REST that's often three endpoints and a waterfall. If your page shape is "one resource, deeply nested, consumed one way," REST with a BFF endpoint is honestly simpler. If it's "many shapes of the same graph, consumed by multiple clients," GraphQL starts paying rent.

How I choose now

The questions that decide it for me:

  • How many consumers? One frontend, simple resources → REST. Multiple clients or wildly varying read shapes → GraphQL.
  • Who owns caching? With REST, HTTP caching and simple request-level caches are easy to reason about. With GraphQL, you're committing to a normalized client cache — powerful, but it's a system you maintain.
  • How strong is your schema discipline? REST without a shared contract (OpenAPI, or at minimum typed transformers on the Laravel side) drifts. GraphQL enforces more discipline by default.
  • Team familiarity. A team fluent in REST will ship GraphQL slowly and vice versa. The theoretical superiority of a contract doesn't compensate for a team fighting its tools.

One rule underneath both

Whatever the protocol, the contract is the product. On the REST projects I've maintained Laravel transformers and request validation as the contract; on GraphQL, the schema. Types flow from that contract into the Next.js side, and anything that bypasses the contract — ad-hoc any casts, hand-rolled response parsing in a component — is debt with interest.

Pick the protocol your problem deserves. Then treat the contract as the part you never skip.