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

# React SDK - Getting started with Next.js

> From an empty Next.js app to a page that reads a flag and a config, updated live, and a route handler that reads a secret.

This walkthrough starts from an empty Next.js app (App Router) and ends with a page that shows a
flag and a config value and re-renders the moment either changes in the Nexus console. The last
part adds the server side: a route handler that reads a secret through the Node.js SDK. A Vite
variant is at the end.

You need Node.js 20.19 or newer, and a **frontend** service in Nexus with a public key (`wxp_...`).
For the server-side part, a **backend** service with a secret key (`wxs_...`) as well.

## 1. Create the app

```bash theme={null}
npx create-next-app@latest checkout --yes
cd checkout
```

## 2. Point npm at the registry and install

The packages are served from the GitLab package registry of the `westyx/nexus/sdk` group, which
serves every `@westyx-nexus` package from one URL. Create `.npmrc` next to `package.json` (it holds
no credentials - commit it):

```
@westyx-nexus:registry=https://gitlab.com/api/v4/groups/131760593/-/packages/npm/
```

```bash theme={null}
npm install @westyx-nexus/sdk-react
```

## 3. Put the endpoint and the key in `.env.local`

In the Nexus console, open the frontend service: its endpoint is on the service page, and the public
key is created under **API keys**. Next.js inlines `NEXT_PUBLIC_` variables into the browser bundle
at build time, which is fine here: the endpoint and a `wxp_` key are public by design, and a public
key never receives a secret.

```bash .env.local theme={null}
NEXT_PUBLIC_NEXUS_BASE_URL=https://blue-ocean-a5rx7.westyx.dev
NEXT_PUBLIC_NEXUS_API_KEY=wxp_...
```

## 4. Wrap the app in `NexusProvider`

`app/layout.tsx` stays a Server Component. The SDK's build is marked `'use client'`, so the provider
renders as a client boundary without a wrapper file of your own.

```tsx app/layout.tsx theme={null}
import type { ReactNode } from 'react';
import { NexusProvider } from '@westyx-nexus/sdk-react';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <NexusProvider
          config={{
            baseUrl: process.env.NEXT_PUBLIC_NEXUS_BASE_URL!,
            apiKey: process.env.NEXT_PUBLIC_NEXUS_API_KEY!,
          }}
          loadingFallback={<p>Loading...</p>}
        >
          {children}
        </NexusProvider>
      </body>
    </html>
  );
}
```

The provider runs the first sync before it renders `children`, so no component shows a default it
would immediately replace; `loadingFallback` covers that moment. A server render produces
`loadingFallback` only - the client is created in the browser.

## 5. Read a flag and a config

Hooks run in Client Components, so the page starts with `'use client'`:

```tsx app/page.tsx theme={null}
'use client';

import { useConfig, useFlag, useNexusStreamStatus } from '@westyx-nexus/sdk-react';

export default function Home() {
  const newCheckout = useFlag('new.checkout');
  const currency = useConfig<string>('checkout.currency') ?? 'EUR';
  const { connected } = useNexusStreamStatus();

  return (
    <main>
      <p>{newCheckout ? 'New checkout' : 'Classic checkout'} - prices in {currency}</p>
      <small>{connected ? 'Live' : 'Polling'}</small>
    </main>
  );
}
```

`useFlag` returns `false` (or the second argument) for a flag the service does not define;
`useConfig` returns `undefined` for a missing key, and its type parameter is a cast, not a check.

## 6. Run it

```bash theme={null}
npm run dev
```

Open `http://localhost:3000`. The page shows the flag and the currency, and the badge reads
**Live** once the update stream is connected. Toggle `new.checkout` in the console: the page
re-renders within a second, without a reload.

## When it does not work

| What you see | Cause | Fix |
| - | - | - |
| `npm install` answers `404 Not Found` | `.npmrc` is missing or names another registry | Step 2; check `npm config get @westyx-nexus:registry` |
| `NexusInitError: nexus: initial sync failed` with `cause` `NexusDevSessionError: nexus: /__westyx is not proxied ...` | Neither variable is read, so the SDK takes the [local development](https://docs.westyx.dev/sdks/react/configuration.md#local-development) path: `.env.local` is missing, the names lack the `NEXT_PUBLIC_` prefix, or the dev server was started before the file existed | Fix the names and restart `npm run dev` |
| `NexusConfigError: nexus: invalid configuration - apiKey: is required and must be a non-empty string (received "undefined")` | Only `NEXT_PUBLIC_NEXUS_BASE_URL` is read: the key's variable is misspelled or lacks the `NEXT_PUBLIC_` prefix (`baseUrl` instead of `apiKey` in the message means the opposite) | Fix the name and restart `npm run dev` |
| `NexusConfigError: ... apiKey: browser SDKs require a public key (wxp_...) ... (received "wxs_...")` | A secret key in browser code | Create a public key on the frontend service; secret keys belong in the server-side part below |
| `NexusInitError: nexus: initial sync failed` with `cause` `NexusUnauthorizedError: nexus: unauthorized - invalid API key or endpoint mismatch` | The key belongs to another service, or was revoked | Use the endpoint and the key of the same service |
| The page stays on **Polling**, and the console logs `nexus: live updates could not be established` | The stream request is blocked between the browser and Nexus, often by a proxy or an extension | Values still refresh on the TTL; see [Live updates](https://docs.westyx.dev/sdks/react/sse-live-updates.md) |

Without `onError`, an initialisation failure is re-thrown to the nearest error boundary - for a
provider in the root layout that is `app/global-error.tsx`. Pass
`onError={(err) => <p>{err.message}</p>}` to the provider to render it in place instead.

## The server side: secrets in a route handler

Secrets never reach a browser, so server code reads them with the [Node.js SDK](https://docs.westyx.dev/sdks/nodejs/index.md)
and a secret key of a **backend** service. Install it from the same registry:

```bash theme={null}
npm install @westyx-nexus/sdk-nodejs server-only
```

```bash .env.local theme={null}
NEXUS_ENDPOINT=https://quiet-river-k2m9d.westyx.dev
NEXUS_API_KEY=wxs_...
```

One client per server process. Keeping it on `globalThis` keeps a dev-mode reload from opening a
second one, and `server-only` turns an accidental import from client code into a build error:

```ts lib/nexus.ts theme={null}
import 'server-only';
import { NexusClient } from '@westyx-nexus/sdk-nodejs';

const globalForNexus = globalThis as unknown as { nexus?: Promise<NexusClient> };

export function nexus(): Promise<NexusClient> {
  globalForNexus.nexus ??= NexusClient.create({
    endpoint: process.env.NEXUS_ENDPOINT,
    apiKey: process.env.NEXUS_API_KEY,
  });
  return globalForNexus.nexus;
}
```

```ts app/api/checkout/route.ts theme={null}
import { connection } from 'next/server';
import { nexus } from '@/lib/nexus';

export async function GET() {
  await connection();
  const client = await nexus();
  return Response.json({
    newCheckout: client.getFlag('new.checkout'),
    paymentConfigured: client.getSecret('payment.api_key').length > 0,
  });
}
```

`await connection()` marks the handler dynamic, so it runs per request rather than once at build
time. The same `nexus()` works in a Server Component. The Node.js client keeps its own live stream,
so the values it returns are as current as the browser's.

## Production

`NEXT_PUBLIC_` values are fixed when `next build` runs, so set them in the build environment of each
deployment. `NEXUS_ENDPOINT` and `NEXUS_API_KEY` are read at run time; set them on the server, never
in a file that is committed.

## Which API to use

| You need | Use |
| - | - |
| Flags and configs in React components | `NexusProvider` and the hooks - this page |
| A value outside React (a data loader, a plain module) | `useNexus()` inside the tree, or `NexusClient.create(config)` and `close()` yourself - see [API reference](https://docs.westyx.dev/sdks/react/api-reference.md#nexusclient) |
| The OpenFeature API in components | The [OpenFeature bridge](https://docs.westyx.dev/sdks/react/openfeature.md) on top of `NexusProvider` |
| Secrets, or flags in server code | The [Node.js SDK](https://docs.westyx.dev/sdks/nodejs/index.md), as in the server-side part above |
| Local development without a key in `.env.local` | `westyx dev run` and a proxy entry - see [Local development](https://docs.westyx.dev/sdks/react/configuration.md#local-development) |

## Vite

With Vite the steps are the same up to the environment: the variables carry the `VITE_` prefix in
`.env.local`, and the provider wraps the app in `src/main.tsx`.

```bash .env.local theme={null}
VITE_NEXUS_BASE_URL=https://blue-ocean-a5rx7.westyx.dev
VITE_NEXUS_API_KEY=wxp_...
```

```tsx src/main.tsx theme={null}
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { NexusProvider } from '@westyx-nexus/sdk-react';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <NexusProvider
      config={{
        baseUrl: import.meta.env.VITE_NEXUS_BASE_URL,
        apiKey: import.meta.env.VITE_NEXUS_API_KEY,
      }}
      loadingFallback={<p>Loading...</p>}
    >
      <App />
    </NexusProvider>
  </StrictMode>,
);
```

`App` reads values with the same hooks as step 5, without the `'use client'` line.

## Next

> [card] [Configuration](https://docs.westyx.dev/sdks/react/configuration.md)
>
> Every option, the deadlines, and local development without a key.

> [card] [API reference](https://docs.westyx.dev/sdks/react/api-reference.md)
>
> Every hook, the client, and the types.

> [card] [Caching behaviour](https://docs.westyx.dev/sdks/react/caching-behaviour.md)
>
> When values refresh, and what happens when the server pushes back.

> [card] [OpenFeature](https://docs.westyx.dev/sdks/react/openfeature.md)
>
> The bridge provider and per-user targeting.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.