> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chipipay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Server SDK (createChipiServer)

> Create a server-side Chipi SDK singleton for use in Next.js Server Components and Route Handlers.

## Overview

`createChipiServer` provides a singleton `ChipiServerSDK` instance for server-side operations in Next.js. It ensures only one SDK instance exists across your application, with automatic config conflict detection.

Import everything from `@chipi-stack/nextjs/server`:

```typescript theme={null}
import {
  createChipiServer,
  getChipiServer,
  resetChipiServer,
} from "@chipi-stack/nextjs/server";
```

## Setup

Create a shared server configuration file (e.g. `lib/chipi-server.ts`):

```typescript theme={null}
import { createChipiServer } from "@chipi-stack/nextjs/server";

export const chipiServer = createChipiServer({
  apiPublicKey: process.env.CHIPI_PUBLIC_KEY!,
  apiSecretKey: process.env.CHIPI_SECRET_KEY!,
});
```

<Warning>
  `apiPublicKey` and `apiSecretKey` are both required. The function throws
  immediately if either is missing. Keep `apiSecretKey` server-only — never
  expose it in client bundles or `NEXT_PUBLIC_*` environment variables.
</Warning>

## Functions

### `createChipiServer(config)`

Creates or returns the singleton `ChipiServerSDK` instance.

| Parameter      | Type     | Required | Description                    |
| -------------- | -------- | -------- | ------------------------------ |
| `apiPublicKey` | `string` | Yes      | Your Chipi public API key      |
| `apiSecretKey` | `string` | Yes      | Your Chipi secret API key      |
| `alphaUrl`     | `string` | No       | Custom API base URL (advanced) |
| `nodeUrl`      | `string` | No       | Custom Starknet RPC node URL   |

**Returns:** `ChipiServerSDK`

#### Config Conflict Detection

If `createChipiServer` is called a second time with a different config, it throws an error instead of silently ignoring the new config. This prevents hard-to-debug issues where different parts of your app expect different configurations.

```typescript theme={null}
// First call — creates the singleton
createChipiServer({ apiPublicKey: "pk_1", apiSecretKey: "sk_1" });

// Second call with same config — returns the existing instance (no-op)
createChipiServer({ apiPublicKey: "pk_1", apiSecretKey: "sk_1" });

// Second call with different config — throws an error
createChipiServer({ apiPublicKey: "pk_2", apiSecretKey: "sk_2" });
// Error: createChipiServer() was called with a different config than the
// existing singleton. Call resetChipiServer() first if you need to reconfigure.
```

### `getChipiServer()`

Returns the existing singleton instance. Throws if `createChipiServer` has not been called yet.

**Returns:** `ChipiServerSDK`

```typescript theme={null}
import { getChipiServer } from "@chipi-stack/nextjs/server";

// In any server-side code after initial setup
const chipi = getChipiServer();
```

### `resetChipiServer()`

Destroys the existing singleton instance so that a new one can be created with `createChipiServer`. Primarily useful for testing.

```typescript theme={null}
import { resetChipiServer, createChipiServer } from "@chipi-stack/nextjs/server";

// In a test setup / teardown
resetChipiServer();
const freshInstance = createChipiServer({ /* new config */ });
```

## Usage in Server Components

```typescript theme={null}
import { chipiServer } from "@/lib/chipi-server";

export default async function WalletPage({ params }: { params: { userId: string } }) {
  const wallet = await chipiServer.wallets.getWallet({
    externalUserId: params.userId,
  });

  return (
    <div>
      <h1>Wallet</h1>
      {/* GetWalletResponse exposes `publicKey` and `normalizedPublicKey`. */}
      {/* There is no `accountAddress` field — see types/src/wallet.ts. */}
      <p>Address: {wallet.normalizedPublicKey}</p>
      <p>Public Key: {wallet.publicKey}</p>
    </div>
  );
}
```

## Usage in Route Handlers

```typescript theme={null}
import { chipiServer } from "@/lib/chipi-server";
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  const { externalUserId } = await request.json();

  const wallet = await chipiServer.wallets.createWallet({
    externalUserId,
  });

  return NextResponse.json(wallet);
}
```

## Usage in Server Actions

```typescript theme={null}
"use server";

import { chipiServer } from "@/lib/chipi-server";
import { Chain, ChainToken } from "@chipi-stack/backend";

export async function getWalletBalance(userId: string) {
  const balance = await chipiServer.getTokenBalance({
    externalUserId: userId,
    chainToken: ChainToken.USDC,
    chain: Chain.STARKNET,
  });

  return balance;
}
```

## Related

* [Backend SDK Quickstart](/sdk/backend/quickstart) — Full backend SDK reference
* [Next.js Introduction](/sdk/nextjs/introduction) — Client-side Next.js SDK setup
