fullauth / DOCS / Next.js / Usage
GitHub

DOCUMENTATION / NEXT.JS

Next.js usage

The React helpers are client-side APIs. Wrap the app in the SessionProvider shown in the installation guide before calling useSession.

Sign in with credentials

The example receives form values as props. Connect those props to your own form; credentials verification runs in the application callback configured on the server.

app/components/SignInButton.tsx

'use client';

import { signIn } from '@fullauth/react';

export default function SignInButton({
  email,
  password,
}: {
  email: string;
  password: string;
}) {
  return (
    <button
      onClick={() =>
        signIn('credentials', { credentials: { email, password } })
      }
    >
      Sign in
    </button>
  );
}

Sign out

app/components/SignOutButton.tsx

'use client';

import { signOut } from '@fullauth/react';

export default function SignOutButton() {
  return <button onClick={() => signOut()}>Sign out</button>;
}

Read the client session

app/components/SessionStatus.tsx

'use client';

import { useSession } from '@fullauth/react';

export default function SessionStatus() {
  const { session, status } = useSession();
  const label = session?.user?.email ?? status;

  return <p>{label}</p>;
}

Update session data

update(data) sends the data to the server. The application’s callbacks.token callback receives it in updates; validate and merge only the fields your app intends to accept. The default callback does not merge arbitrary update data into the token.

app/components/RenameSession.tsx

'use client';

import { useSession } from '@fullauth/react';

export default function RenameSession() {
  const { update } = useSession();

  return (
    <button onClick={() => update({ name: 'New name' })}>
      Update session
    </button>
  );
}

Read a session on the server

getServerSession accepts the configured secret and returns a session or null. It can also be called with a request in the helper’s overload.

app/account/page.tsx

import { getServerSession } from '@fullauth/next/helpers';
import { authOptions } from '../api/auth/[...fullauth]/route';

export default async function AccountPage() {
  const session = await getServerSession(authOptions.secret!);
  return <p>{session?.user?.email ?? 'Signed out'}</p>;
}

TypeScript signatures

import type { Session } from '@fullauth/core';
import type { NextRequest } from 'next/server';

declare function getServerSession(secret: string): Promise<Session | null>;
declare function getServerSession(
  secret: string,
  req: Request | NextRequest,
): Promise<Session | null>;