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

# Next.js

> Integrate Timeback with Next.js App Router

## Overview

The Timeback SDK provides a Next.js adapter for the App Router with route handlers.

If you are using coding agents, pair this page with [`timeback-server`](https://github.com/superbuilders/timeback-sdk-skills/tree/main/skills/timeback/timeback-server) from the [AI Skills](https://docs.timeback.com/beta/build-on-timeback/ai/skills.md) catalog.

## Installation

```bash npm theme={null}
npm install @timeback/sdk
```

```bash pnpm theme={null}
pnpm add @timeback/sdk
```

```bash yarn theme={null}
yarn add @timeback/sdk
```

```bash bun theme={null}
bun add @timeback/sdk
```

## Server Setup

Create a server-only Timeback instance. The session helpers below belong to your application: persist the callback user in your authenticated session, and return that session user (including `email`) or `null` from `getUser`. These helpers are not SDK exports. Keep API and SSO secrets on the server:

```typescript lib/timeback.ts theme={null}
import { createTimeback } from '@timeback/sdk'

export const timeback = await createTimeback({
    env: 'staging',
    api: {
        clientId: process.env.TIMEBACK_API_CLIENT_ID!,
        clientSecret: process.env.TIMEBACK_API_CLIENT_SECRET!,
    },
    identity: {
        mode: 'sso',
        clientId: process.env.AWS_COGNITO_CLIENT_ID!,
        clientSecret: process.env.AWS_COGNITO_CLIENT_SECRET!,
        redirectUri: 'http://localhost:3000/api/timeback/identity/callback',
        onCallbackSuccess: async ({ user, state, redirect }) => {
            await setSession({ id: user.id, email: user.email })
            return redirect(state?.returnTo ?? '/')
        },
        onCallbackError: ({ error, redirect }) => {
            return redirect('/?error=sso_failed')
        },
        getUser: () => getSession(),
    },
})
```

## Route Handler

Create a catch-all route handler:

```typescript app/api/timeback/[...timeback]/route.ts theme={null}
import { toNextjsHandler } from '@timeback/sdk/nextjs'

import { timeback } from '@/lib/timeback'

export const { GET, POST, PUT, DELETE, PATCH } = toNextjsHandler(timeback)
```

This handles all Timeback routes:

| Route | Method | Purpose |
| - | - | - |
| `/api/timeback/identity/signin` | GET | Initiates SSO flow |
| `/api/timeback/identity/callback` | GET | Handles SSO callback |
| `/api/timeback/identity/signout` | GET | Initiates Timeback sign-out |
| `/api/timeback/user/verify` | GET | Verifies user session |
| `/api/timeback/user/me` | GET | Fetches user profile |
| `/api/timeback/activity/heartbeat` | POST | Time-spent heartbeat |
| `/api/timeback/activity/submit` | POST | Activity completion submit |

## Client Provider

Wrap your app with the TimebackProvider:

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

import { TimebackProvider } from '@timeback/sdk/react'

export function Providers({ children }: { children: React.ReactNode }) {
    return <TimebackProvider>{children}</TimebackProvider>
}
```

```tsx app/layout.tsx theme={null}
import { Providers } from './providers'

export default function RootLayout({ children }) {
    return (
        <html>
            <body>
                <Providers>{children}</Providers>
            </body>
        </html>
    )
}
```

## Usage

> [!TIP]
>
> For the full client-side API, see the [React client
> adapter](https://docs.timeback.com/beta/build-on-timeback/sdk/client/react.md).

Use hooks in client components:

```tsx components/UserStatus.tsx theme={null}
'use client'

import { SignInButton, useTimebackVerification } from '@timeback/sdk/react'

export function UserStatus() {
    const { state } = useTimebackVerification()

    if (state.status === 'loading') return <div>Loading...</div>
    if (state.status === 'error') return <div>{state.message}</div>
    if (state.status !== 'verified') {
        return <SignInButton>Sign In</SignInButton>
    }

    return <div>Welcome!</div>
}
```

## Next Steps

> [card] [React Client](https://docs.timeback.com/beta/build-on-timeback/sdk/client/react.md)
>
> Client-side React integration

> [card] [Identity](https://docs.timeback.com/beta/build-on-timeback/sdk/identity.md)
>
> Authentication options

> [card] [Custom Activities](https://docs.timeback.com/beta/build-on-timeback/sdk/activity-tracking/intro.md)
>
> Track learning sessions
