Docs
Search⌘ K
  • Home
  • About The Graph
  • Supported Networks
  • Protocol Contracts
  • AI Tooling
  • Subgraphs
    • Substreams
      • Indexer Software
        • Gateway Software
          • Data Services
            • Resources
              Subgraphs > Guides & Best Practices

              3 minutes

              Secure API Keys with Next.js Server Components

              An API key in frontend code is visible to anyone who opens the browser’s developer tools. Use Next.js server components⁠ to send Subgraph queries from the server, so the key never reaches the client. For more protection, also restrict your API key to specific Subgraphs or domains in Subgraph Studio.

              This guide shows how to create a Next.js server component that queries a Subgraph while keeping the API key out of the frontend.

              Caveats

              • Next.js server components do not protect API keys from being drained using denial of service attacks.
              • The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections.
              • Next.js server components introduce centralization risks as the server can go down.

              Why It’s Needed

              In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While .env files are commonly used, they don’t fully protect the keys since React’s code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side.

              Using client-side rendering to query a Subgraph

              Client-side rendering

              Prerequisites

              • An API key from Subgraph Studio
              • Basic knowledge of Next.js and React.
              • An existing Next.js project that uses the App Router⁠.

              Step-by-Step Guide

              Step 1: Set Up Environment Variables

              1. In your Next.js project root, create a .env.local file.
              2. Add your API key: API_KEY=<api_key_here>.

              Step 2: Create a Server Component

              1. In your components directory, create a new file, ServerComponent.js.
              2. Use the provided example code to set up the server component.

              Step 3: Implement Server-Side API Request

              In ServerComponent.js, add the following code:

              1const API_KEY = process.env.API_KEY23export default async function ServerComponent() {4  const response = await fetch(5    `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`,6    {7      method: 'POST',8      headers: {9        'Content-Type': 'application/json',10      },11      body: JSON.stringify({12        query: /* GraphQL */ `13          {14            factories(first: 5) {15              id16              poolCount17              txCount18              totalVolumeUSD19            }20          }21        `,22      }),23    },24  )2526  const responseData = await response.json()27  const data = responseData.data2829  return (30    <div>31      <h1>Server Component</h1>32      {data ? (33        <ul>34          {data.factories.map((factory) => (35            <li key={factory.id}>36              <p>ID: {factory.id}</p>37              <p>Pool Count: {factory.poolCount}</p>38              <p>Transaction Count: {factory.txCount}</p>39              <p>Total Volume USD: {factory.totalVolumeUSD}</p>40            </li>41          ))}42        </ul>43      ) : (44        <p>Loading data...</p>45      )}46    </div>47  )48}

              Step 4: Use the Server Component

              1. In your page file (e.g., pages/index.js), import ServerComponent.
              2. Render the component:
              1import ServerComponent from './components/ServerComponent'23export default function Home() {4  return (5    <main>6      <ServerComponent />7    </main>8  )9}

              Step 5: Run and Test Your App

              Start your Next.js application using npm run dev. Verify that the server component is fetching data without exposing the API key.

              Server-side rendering

              The API key now stays on the server, and the browser receives only the query results.

              Learn More

              • Managing API keys: restrict keys by Subgraph and domain, and set spending limits.
              • Querying best practices: write efficient, cacheable queries.
              • Guides & Best Practices overview: the full checklist and how this page fits with the rest of the section.
              ⁠Edit on GitHub⁠

              Pruning with indexerHintsDebug with Subgraph Forking
              On this page
              • Caveats
              • Why It’s Needed
              • Using client-side rendering to query a Subgraph
              • Prerequisites
              • Step-by-Step Guide
              • Step 1: Set Up Environment Variables
              • Step 2: Create a Server Component
              • Step 3: Implement Server-Side API Request
              • Step 4: Use the Server Component
              • Step 5: Run and Test Your App
              • Learn More
              The GraphStatusTestnetBrand AssetsForumSecurityPrivacy PolicyTerms of Service