Beta

Next.js (App Router)

Complete references for Next.js App router SDK

Quickstart

Visit Next.js app router's quickstart page.

References

<CakeAuthProvider />

Component CakeAuthProvider is required to integrate CakeAuth in a React platform. This provider provides contexts and data that being used by various hooks and/or components.

Usage

layout.tsx
import { CakeAuthProvider } from "@cakeauth/nextjs-app"; 
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <CakeAuthProvider

          config={{

            publicKey: process.env.NEXT_PUBLIC_CAKEAUTH_PUBLIC_KEY!, 
          }} 

        >
          {children}

        </CakeAuthProvider>
      </body>
    </html>
  );
}

Properties

PropTypeDefault
children
React.ReactNode
-
config.publicKey
string
-
config.url
string?
Decoded from the public key
config.pages.signin
string?
/
config.pages.signup
string?
/?flow=signup
config.pages.passwordReset
string?
/?flow=password_reset

<SignIn />

Component SignIn is rendering a page of signin screen.

Usage

import { SignIn } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <SignIn />;
};
 
export default Home;

Properties

PropTypeDefault

<SignInCard />

Component SignInCard is rendering a sign in card component (not a whole page like <SignIn />)

Usage

import { SignInCard } from "@cakeauth/nextjs-app"; 
 
const Home = () => {
  return (
    <main>
      {/* Other custom components */}

      <SignInCard />
    </main>
  );
};
 
export default Home;

Properties

PropTypeDefault

<SignUp />

Component SignUp is rendering a page of signup screen.

Usage

import { SignUp } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <SignUp />;
};
 
export default Home;

Properties

PropTypeDefault

<SignUpCard />

Component SignUpCard is rendering a sign up card component (not a whole page like <SignUp />)

Usage

import { SignUpCard } from "@cakeauth/nextjs-app"; 
 
const Home = () => {
  return (
    <main>
      {/* Other custom components */}

      <SignUpCard />
    </main>
  );
};
 
export default Home;

Properties

PropTypeDefault

<PasswordReset />

Component PasswordReset is rendering a page of password reset flow.

Usage

import { PasswordReset } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <PasswordReset />;
};
 
export default Home;

Properties

PropTypeDefault

<PasswordResetCard />

Component PasswordResetCard is rendering a sign up card component (not a whole page like <PasswordReset />).

This component has two main logic:

Usage

import { PasswordResetCard } from "@cakeauth/nextjs-app"; 
 
const Home = () => {
  return (
    <main>
      {/* Other custom components */}

      <PasswordResetCard />
    </main>
  );
};
 
export default Home;

Properties

PropTypeDefault

<Captcha />

The Captcha component, requires the bot protection settings to be configured. Under the hood, it uses:

Usage

import { Captcha } from "@cakeauth/nextjs-app"; 
 
const Home = () => {
  return (
    <main>
      {/* Other custom components */}

      <Captcha type="turnstile" siteKey="xxx" />
    </main>
  );
};
 
export default Home;

Properties

PropTypeDefault
type
turnstile | recaptcha | null | undefined
-
siteKey
string
-
onVerify()
(token: string) => void
-

<SignedIn />

The SignedIn component is a wrapper component that will only renders the children if there's a User with an active Session signed in your application.

Usage

import { SignedIn } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <SignedIn>{/* Your protected components */}</SignedIn>;
};
 
export default Home;

Properties

PropTypeDefault
children
React.ReactNode
-

<SignedOut />

The SignedOut component is a wrapper component that will only renders the children if there's no User with an active Session signed in your application.

Usage

import { SignedOut } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <SignedOut>{/* Your public components */}</SignedOut>;
};
 
export default Home;

Properties

PropTypeDefault
children
React.ReactNode
-

<UserButton />

The UserButton component renders a button which on click displays a dropdown of common quick actions that current users can do. Such as:

  • Manage Account (which renders the <UserDialog />)
  • Signin out

Usage

import { UserButton } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <UserButton />;
};
 
export default Home;

Properties

PropTypeDefault
align
center | end | start | undefined
center
className
string
-

<UserDialog />

The UserDialog component renders a featured users management dialog that allows users to manage their account and sessions.

Currently, users can:

  • See their details
  • Reset password (if current identifier is_password_enabled=true)
  • List their active sessions and revoke a session
  • Signing out (revoking current session)

Usage

import { UserDialog } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <UserDialog />;
};
 
export default Home;

Properties

PropTypeDefault
open
boolean
-
onOpenChange()
(open: boolean) => void
-

<CakeAuthLoaded />

The CakeAuthLoaded component is a wrapper component that will only renders the children when the CakeAuth data has loaded.

Usage

import { CakeAuthLoaded } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <CakeAuthLoaded>{/* Your after load components */}</CakeAuthLoaded>;
};
 
export default Home;

Properties

PropTypeDefault
children
React.ReactNode
-

<CakeAuthLoading />

The CakeAuthLoading component is a wrapper component that will only renders the children when the CakeAuth data is still loading.

Usage

import { CakeAuthLoading } from "@cakeauth/nextjs-app";
 
const Home = () => {
  return <CakeAuthLoading>{/* Your loading components */}</CakeAuthLoading>;
};
 
export default Home;

Properties

PropTypeDefault
children
React.ReactNode
-

createRouteMatcher

A utility function for creating route matchers to handle matching your pathname.

Usage

import { createRouteMatcher } from "@cakeauth/nextjs-app";
 
const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/forum(.*)"]);
const isPublicRoute = createRouteMatcher(["/signin(.*)", "/signup(.*)"]);
 
isPublicRoute(window.location.pathname); // => true or false

Properties

PropTypeDefault
patterns
string[]
-

Returns

PropTypeDefault
(path: string) => boolean
(path: string) => boolean
-

cakeauthMiddleware

Middleware function to handle authentication and route protection in Next.js applications.

Use:

  • auth.protect(): to automatically redirects to signin page if no valid auth credentials found
  • auth.isAuthenticated: to check whether current auth credentials valid

Usage

  • Base usage:
middleware.ts
import { cakeauthMiddleware } from "@cakeauth/nextjs-app";
 
export default cakeauthMiddleware();
 
export const config = {
  matcher: [
    // Skip Next.js internals and all static files, unless found in search params
    "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
    // Always run for API routes
    "/(api|trpc)(.*)",
  ],
};
middleware.ts
import { cakeauthMiddleware, createRouteMatcher } from "@cakeauth/nextjs-app";
 
const isPublicRoute = createRouteMatcher(["/signin(.*)"]);
 
export default cakeauthMiddleware(async (auth, request) => {
  if (!isPublicRoute(request.url)) return auth.protect();
});
 
export const config = {
  matcher: [
    // Skip Next.js internals and all static files, unless found in search params
    "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
    // Always run for API routes
    "/(api|trpc)(.*)",
  ],
};

Types

type AuthProtectOpts = {
  /*
   * @param {boolean} clearSearchParams - Control whether to clear search params
   * on **redirect to sign in**
   *
   * default: false
   */
  clearSearchParams?: boolean;
};
 
type Auth = {
  isAuthenticated: boolean;
  protect: (opts?: AuthProtectOpts) => Promise<NextResponse<unknown>>;
};

Properties

PropTypeDefault
handler
handler?: (auth: Auth, request: Request) => Promise<NextResponse<unknown> | undefined>
-

getOAuthUrl

Function to generate OAuth URLs for various providers. Returns a URL string or null if required parameters are missing.

Usage

import { getOAuthUrl } from "@cakeauth/nextjs-app";
 
const oauthUrl = getOAuthUrl({
  provider: "github",
  clientId: "xxxx",
  redirectUri: "https://example.com/v1/callback",
  scopes: ["user", "email"],
  publicKey: "pub_test_xxx",
});

Properties

PropTypeDefault
provider
github | google
-
clientId
string | null | undefined
-
redirectUri
string | null | undefined
-
scopes
string[]
-
publicKey
string
-

Returns

string | null - The generated OAuth URL or null if required parameters are missing.


useHandshakeExchange

Hook for handling the OAuth handshake exchange process. Read more about handshake exchange process here.

Usage

import { CakeAuth } from "@cakeauth/frontend"
import { useHandshakeExchange } from "@cakeauth/nextjs-app";
 
const cakeauth = new CakeAuth({
  publicKey: "pub_test_xxx"
})
 
const Home = () => {
  const { state, error } = useHandshakeExchange({ cakeauth });
 
  return (
    // ...
  )
};
 
export default Home;

Properties

PropTypeDefault
cakeauth
CakeAuth
-

Returns

PropTypeDefault
state
State
-
error
CakeAuthErrorResponse | null
-

useRefreshAccessToken

Hook for refreshing the access token. Can only being invoked if a valid user sessions is present. Read more about CakAuth refresh token mechanism and process here.

Usage

import { CakeAuth } from "@cakeauth/frontend"
import { useRefreshAccessToken } from "@cakeauth/nextjs-app";
 
const cakeauth = new CakeAuth({
  publicKey: "pub_test_xxx"
})
 
const Home = () => {
  const { state, error } = useRefreshAccessToken({ cakeauth });
 
  return (
    // ...
  )
};
 
export default Home;

Properties

PropTypeDefault
cakeauth
CakeAuth
-

Returns

PropTypeDefault
state
State
-
error
CakeAuthErrorResponse | null
-

useSession

React hook that provides authentication session state and data.

Usage

import { useSession } from "@cakeauth/nextjs-app";
 
const Home = () => {
  const { isAuthenticated, state, error, value } = useSession();
 
  return (
    // ...
  )
}
 
export default Home;

Returns

PropTypeDefault
isAuthenticated
boolean
-
state
State
-
error
Error | null
-
value.sessionId
string
-
value.userId
string
-
value.accessToken
string
-

useSettings

Hook for getting current environment [settings details](/frontend#tag/settings/GET/v1/settings.

Usage

import { useSettings } from "@cakeauth/nextjs-app";
 
const { value, state, error } = useSettings();

Types

Returns

PropTypeDefault
value
GetSettingsResponse | null
-
state
State
-
error
CakeAuthErrorResponse | null
-

useSignout

Hook for handling user sign out.

Usage

import { useSignout } from "@cakeauth/nextjs-app";
 
const Home = () => {
  const { signout, state, error } = useSignout();
 
  return (
    // ...
  )
}
 
export default Home;

Returns

PropTypeDefault
state
State
-
error
CakeAuthErrorResponse | null
-
signout()
() => Promise<void>
-

useUser

Hook for accessing the current user data.

Usage

import { useUser } from "@cakeauth/nextjs-app";
 
const Home = () => {
  const { value, state, error } = useUser();
 
  return (
    // ...
  )
}
 
export default Home;

Types

Returns

PropTypeDefault
state
State
-
error
CakeAuthErrorResponse | null
-
value
GetMeResponseItem | null
-

I'll create documentation for both OAuth URL generator functions.

getGithubOAuthUrl

Function to generate GitHub OAuth URLs with required state parameters.

Usage

import { getGithubOAuthUrl } from "@cakeauth/nextjs-app";
 
const url = getGithubOAuthUrl({
  clientId: "xxxx",
  redirectUri: "https://example.com/v1/callback",
  scope: ["user", "email"],
  config: {
    origin: "https://myapp.com",
    csrf_token: "random_token",
    provider: "github",
    public_key: "pub_test_xxx",
  },
});

Properties

PropTypeDefault
clientId
string
-
redirectUri
string
-
scope
string[]
-
config.origin
string
-
config.csrf_token
string
-
config.provider
"github"
-
config.user_agent
string
-
config.public_key
string
-

Returns

string - The generated GitHub OAuth URL

getGoogleOAuthUrl

Function to generate Google OAuth URLs with required state parameters.

Usage

import { getGoogleOAuthUrl } from "@cakeauth/nextjs-app";
 
const url = getGoogleOAuthUrl({
  clientId: "xxx",
  redirectUri: "https://example.com/v1/callback",
  scope: ["profile", "email"],
  access_type: "offline",
  config: {
    origin: "https://myapp.com",
    csrf_token: "random_token",
    provider: "google",
    public_key: "pub_test_xxx",
  },
});

Properties

PropTypeDefault
clientId
string
-
redirectUri
string
-
scope
string[]
-
config.origin
string
-
config.csrf_token
string
-
config.provider
"github"
-
config.user_agent
string
-
config.public_key
string
-

Returns

string - The generated Google OAuth URL


redirectTo

Utility function for handling redirects in the application. A thin wrapper to the web Response interface.

Usage

import { redirectTo } from "@cakeauth/nextjs-app";
 
redirectTo("https://example.com/dashboard");

Parameters

PropTypeDefault
path
string
-

Last updated on