Skip to content

Commit

Permalink
Added 'How to Secure API Keys Using NextJS Server Components' Cookbook (
Browse files Browse the repository at this point in the history
#587)

* Added 'How to Secure API Keys Using NextJS Server Components' Cookbook

* Add NextJS server component security caveats

* Corrected linting errors

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Noted.

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Noted.

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

* Update website/pages/en/cookbook/how-to-secure-api-keys-using-nextjs-server-components.mdx

Co-authored-by: Benoît Rouleau <[email protected]>

---------

Co-authored-by: Benoît Rouleau <[email protected]>
  • Loading branch information
marcusrein and benface authored Jan 19, 2024
1 parent 9981404 commit 3f95eb7
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
---
title: How to Secure API Keys Using Next.js Server Components
---

## Overview

We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key).

In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from 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](/img/api-key-client-side-rendering.png)

### Prerequisites

- An API key from [Subgraph Studio](https://thegraph.com/studio)
- Basic knowledge of Next.js and React.
- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app).

## Step-by-Step Cookbook

### Step 1: Set Up Environment Variables

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

### Step 2: Create a Server Component

1. In our `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:

```javascript
import React from "react";

const API_KEY = process.env.API_KEY;

export default async function ServerComponent() {
const response = await fetch(
`https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `
{
factories(first: 5) {
id
poolCount
txCount
totalVolumeUSD
}
}
`,
}),
}
);

const responseData = await response.json();
const data = responseData.data;

return (
<div>
<h1>Server Component</h1>
{data ? (
<ul>
{data.factories.map((factory: any) => (
<li key={factory.id}>
<p>ID: {factory.id}</p>
<p>Pool Count: {factory.poolCount}</p>
<p>Transaction Count: {factory.txCount}</p>
<p>Total Volume USD: {factory.totalVolumeUSD}</p>
</li>
))}
</ul>
) : (
<p>Loading data...</p>
)}
</div>
);
}
```

### Step 4: Use the Server Component

1. In our page file (e.g., `pages/index.js`), import `ServerComponent`.
2. Render the component:

```javascript
import ServerComponent from './components/ServerComponent'

export default function Home() {
return (
<main>
<ServerComponent />
</main>
)
}
```

### Step 5: Run and Test Our Dapp

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

![Server-side rendering](/img/api-key-server-side-rendering.png)

### Conclusion

By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/cookbook/upgrading-a-subgraph/#securing-your-api-key) to increase your API key security even further.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 3f95eb7

Please sign in to comment.