Next.js guide

    Read Google Sheets as JSON in Next.js

    Call SheetsDB from a Next.js route handler so the API key stays on the server. The route can then return the Sheet rows to your application or cache them on your own schedule.

    By Zainul Ariffin
    Keep the key on the server. Do not prefix it with NEXT_PUBLIC_. That would place the key in browser JavaScript.

    Set the environment variables

    .env.local
    SHEETSDB_API_KEY=your_api_key
    GOOGLE_SHEET_URL=https://docs.google.com/spreadsheets/d/.../edit

    Add a route handler

    Create app/api/sheet/route.ts and keep the upstream status code when returning an error.

    TypeScript
    import { NextResponse } from "next/server";
    
    export async function GET() {
      const response = await fetch("https://www.sheetsdb.io/api/v1/getsheet", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.SHEETSDB_API_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          sheetRef: process.env.GOOGLE_SHEET_URL,
          hasHeader: true,
        }),
        cache: "no-store",
      });
    
      const data = await response.json();
    
      if (!response.ok) {
        return NextResponse.json(data, { status: response.status });
      }
    
      return NextResponse.json(data);
    }

    Choose a cache policy

    The example uses cache: "no-store", so each request asks SheetsDB for the current Sheet. For content that changes less often, use a server cache or Next.js revalidation period that fits your application.

    Handle failure states

    The error response contains a stable code and a readable error. Keep the upstream status instead of changing every failure to 500. Handle the code: UNAUTHORIZED needs an API key fix; INVALID_REQUEST or SHEET_UNAVAILABLE needs a request or Sheet-access fix; RATE_LIMITED should wait for Retry-After.