> ## 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](/beta/build-on-timeback/ai/skills) catalog.

## Installation

<CodeGroup>
  ```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
  ```
</CodeGroup>

## Server Setup

Create a Timeback instance:

```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/POST | Signs out user             |
| `/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](/beta/build-on-timeback/sdk/client/react).
</Tip>

Use hooks in client components:

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

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

export function UserStatus() {
	const timeback = useTimeback()

	if (!timeback) {
		return <SignInButton>Sign In</SignInButton>
	}

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

## Next Steps

<CardGroup cols={2}>
  <Card title="React Client" href="/beta/build-on-timeback/sdk/client/react">
    Client-side React integration
  </Card>

  <Card title="Identity" href="/beta/build-on-timeback/sdk/identity">
    Authentication options
  </Card>

  <Card title="Custom Activities" href="/beta/build-on-timeback/sdk/activity-tracking/intro">
    Track learning sessions
  </Card>
</CardGroup>
