@wristband/nextjs-auth
Version:
SDK for integrating your Next.js application with Wristband. Handles user authentication, session management, and token management.
197 lines (196 loc) • 8.2 kB
TypeScript
import { SessionData, SessionOptions } from '@wristband/typescript-session';
import { MutableSession, NextJsCookieStore, ReadOnlySession } from '../types';
/**
* Get a read-only session from Next.js cookies() API.
*
* **For App Router Server Components only** - when you need to READ session data.
* Cannot modify or save. For modifying sessions in Server Actions, use getMutableSessionFromCookies().
*
* For route handlers or middleware/proxy, use getSession() instead.
* For Pages Router, use getPagesRouterSession() instead.
*
* **IMPORTANT:** Using `cookies()` automatically makes your Server Component dynamic (no static caching).
* The route will execute fresh on every request, ensuring session data is always current.
*
* @template T - Session data type extending SessionData
* @param cookieStore - The result of `await cookies()` from 'next/headers'
* @param options - Session configuration options
* @returns Promise resolving to a read-only session with runtime protection against mutations
*
* @example
* ```typescript
* // ✅ Server Component - reading session data
* import { cookies } from 'next/headers';
* import { getReadOnlySessionFromCookies } from '@wristband/nextjs-auth';
*
* const sessionOptions = {
* secrets: process.env.SESSION_SECRET!,
* cookieName: 'my-session'
* };
*
* export default async function ProfilePage() {
* const cookieStore = await cookies();
* const session = await getReadOnlySessionFromCookies(cookieStore, sessionOptions);
* return <div>User: {session.userId}</div>;
* }
*
* // ❌ These will throw TypeScript errors:
* // session.set('theme', 'dark');
* // await session.save();
* ```
* @see {@link getMutableSessionFromCookies} For Server Actions that need to modify sessions
* @see {@link getSessionFromRequest} For App Router route handlers and middleware/proxy
* @see {@link getPagesRouterSession} For Pages Router
*/
export declare function getReadOnlySessionFromCookies<T extends SessionData = SessionData>(cookieStore: NextJsCookieStore, options: SessionOptions): Promise<ReadOnlySession<T>>;
/**
* Get a mutable session from Next.js cookies() API.
*
* **For App Router Server Actions only** - when you need to MODIFY session data.
* Can call set()/delete(), but must use saveSessionWithCookies() to persist changes
* or destroySessionWithCookies() to destroy the session.
*
* For route handlers or middleware/proxy, use getSession() instead.
* For Pages Router, use getPagesRouterSession() instead.
*
* **Cache Behavior:** Server Actions automatically trigger a router refresh when cookies are modified,
* so the UI will update to reflect session changes without manual revalidation. If you have cached
* data that depends on session values, you can optionally call `revalidatePath()` or `revalidateTag()`.
*
* @template T - Session data type extending SessionData
* @param cookieStore - The result of `await cookies()` from 'next/headers'
* @param options - Session configuration options
* @returns Promise resolving to a mutable session that can be modified and saved
* @throws {WristbandError} If an invalid session method is invoked.
*
* @example
* ```typescript
* // Server Action - modifying session data
* 'use server'
* import { cookies } from 'next/headers';
* import {
* getMutableSessionFromCookies,
* saveSessionWithCookies
* } from '@wristband/nextjs-auth';
*
* const sessionOptions = {
* secrets: process.env.SESSION_SECRET!,
* cookieName: 'my-session'
* };
*
* export async function updateUserPreferences(theme: string, language: string) {
* const cookieStore = await cookies();
* const session = await getMutableSessionFromCookies(cookieStore, sessionOptions);
*
* // ✅ Modify session data
* session.set('theme', theme);
* session.set('language', language);
*
* // ✅ Persist changes
* await saveSessionWithCookies(cookieStore, session);
*
* // Optional: revalidate cached data if you have OTHER data that depends on session
* // revalidatePath('/settings'); <- Next.js function
*
* // ❌ These will throw TypeScript errors:
* // await session.save(); -> Use saveSessionWithCookies(cookieStore, session) instead
* // session.destroy(); -> Use destroySessionWithCookies(cookieStore, session) instead
* }
* ```
*
* @see {@link saveSessionWithCookies} To persist session changes
* @see {@link destroySessionWithCookies} To destroy the session
* @see {@link getReadOnlySessionFromCookies} For Server Components (read-only)
*/
export declare function getMutableSessionFromCookies<T extends SessionData = SessionData>(cookieStore: NextJsCookieStore, options: SessionOptions): Promise<MutableSession<T>>;
/**
* Save session changes to Next.js cookies API.
*
* **For App Router Server Actions only.**
* Encrypts and saves session data to cookies using Next.js `cookies()` API.
*
* For App Router route handlers and middleware/proxy, use session.saveToResponse() instead.
* For Pages Router route handlers, use session.save().
*
* **Cache Behavior:** Modifying cookies automatically invalidates Next.js Router Cache
* and triggers a re-render of the current route, so UI updates reflect session changes
* without manual revalidation.
*
* @template T - Session data type extending SessionData
* @param cookieStore - The result of await cookies() from 'next/headers'
* @param session - The session instance to save
* @returns Promise that resolves when cookies are set
* @throws {WristbandError} If session is from a Server Component (read-only)
*
* @example
* ```typescript
* // app/actions.ts
* 'use server'
* import { cookies } from 'next/headers';
* import {
* getMutableSessionFromCookies,
* saveSessionWithCookies
* } from '@wristband/nextjs-auth';
*
* const sessionOptions = {
* secrets: process.env.SESSION_SECRET!,
* cookieName: 'my-session'
* };
*
* export async function updateTheme(theme: string) {
* const cookieStore = await cookies();
* const session = await getMutableSessionFromCookies(cookieStore, sessionOptions);
*
* session.set('theme', theme);
* await saveSessionWithCookies(cookieStore, session);
*
* // UI automatically updates - no manual revalidation needed.
* }
* ```
*
* @see {@link getMutableSessionFromCookies} To get a mutable session
* @see {@link destroySessionWithCookies} To destroy the session instead
*/
export declare function saveSessionWithCookies<T extends SessionData = SessionData>(cookieStore: NextJsCookieStore, session: MutableSession<T>): Promise<void>;
/**
* Destroy session using Next.js cookies API.
*
* **For App Router Server Actions only.**
* Clears session cookies using Next.js `cookies()` API.
*
* For App Router route handlers and middleware/proxy, use session.destroyToResponse() instead.
* For Pages Router route handlers, use session.destroy().
*
* **Cache Behavior:** Deleting cookies automatically invalidates Next.js Router Cache
* and triggers a re-render of the current route.
*
* @template T - Session data type extending SessionData
* @param cookieStore - The result of `await cookies()` from 'next/headers'
* @param session - The session instance to destroy
* @throws {WristbandError} If session is from a Server Component (read-only)
*
* @example
* ```typescript
* 'use server'
* import { cookies } from 'next/headers';
* import { getMutableSessionFromCookies, destroySessionWithCookies } from '@wristband/nextjs-auth';
* import { redirect } from 'next/navigation';
*
* const sessionOptions = {
* secrets: process.env.SESSION_SECRET!,
* cookieName: 'my-session'
* };
*
* export async function logout() {
* const cookieStore = await cookies();
* const session = await getMutableSessionFromCookies(cookieStore, sessionOptions);
*
* destroySessionWithCookies(cookieStore, session);
* redirect('/login');
* }
* ```
*
* @see {@link getMutableSessionFromCookies} To get a mutable session
* @see {@link saveSessionWithCookies} To save session changes instead
*/
export declare function destroySessionWithCookies<T extends SessionData = SessionData>(cookieStore: NextJsCookieStore, session: MutableSession<T>): void;