> Set up the Pylo Next.js SDK with codegen, server client, hooks, and the API route

# Next.js Quickstart

The Next.js SDK (`@pylo/nextjs`) gives you type-safe data access and React Query hooks without
hand-written GraphQL.

> **Authentication**
> For user login, set up [Authentication](/authentication/nextjs-setup) first. The SDK also works
> without user auth by using an API token.

## Install

```bash
# pnpm
pnpm add @pylo/nextjs @tanstack/react-query
# npm
npm install @pylo/nextjs @tanstack/react-query
# yarn
yarn add @pylo/nextjs @tanstack/react-query
```

## 1. Generate types

Create an API token in **Settings > API Tokens** in the admin panel (see
[API Tokens](/authentication/api-tokens)) and put it in `.env.local`.

```bash filename=".env.local"
PYLO_API_KEY=your-api-token-here
```

```typescript filename="pylo.config.ts"
import { defineConfig } from '@pylo/nextjs/codegen';

export default defineConfig({
  apiKey: process.env.PYLO_API_KEY!,
  output: '.pylo', // optional, defaults to '.pylo'
});
```

`pylo generate` loads `.env` and `.env.local` before reading the config.

```bash
# pnpm
pnpm exec pylo generate
# npm
npx pylo generate
# yarn
yarn pylo generate
```

This creates a `.pylo/` directory:

```
.pylo/
  index.ts     # PyloSchema interface + type re-exports
  entities.ts  # Individual entity interfaces
```

> **When to regenerate**
> Rerun `pylo generate` after changing entities or fields in Pylo. Add it as a `prebuild` script for
> CI.

## 2. Server client

For Server Components and Server Actions:

```typescript filename="lib/pylo.ts"
import { createPyloServer } from '@pylo/nextjs/server';
import type { PyloSchema } from '../.pylo';

export const pylo = createPyloServer<PyloSchema>({});
```

## 3. Client hooks

For Client Components:

```typescript filename="lib/pylo-hooks.ts"
import { createPyloHooks } from '@pylo/nextjs/hooks';
import type { PyloSchema } from '../.pylo';

export const pylo = createPyloHooks<PyloSchema>({});
```

> **React Query provider**
> Wrap your app with `QueryClientProvider` from `@tanstack/react-query`. See the [React Query
> docs](https://tanstack.com/query/latest/docs/framework/react/quick-start).

## 4. API route

The GraphQL proxy route the client hooks call:

```typescript filename="app/api/graphql/route.ts"
import { createPyloApiRoute } from '@pylo/nextjs/api';

export const { POST } = createPyloApiRoute();
```

Next: [Querying](/data/querying)
