Beta

Quickstart

Next.js (app router)

Integrate CakeAuth into your Next.js app in just a few steps!

Before continuing

Make sure you have:


Install the package

Currently, we only support Next.js 13 and above with the app router. Older verisons of Next.js or using pages router still not supported.

npm install @cakeauth/nextjs-app

Setup environment variables

In your .env.local file (create one if it doesn't exist), add the following:

NEXT_PUBLIC_CAKEAUTH_PUBLIC_KEY="pub_test_xxx"
CAKEAUTH_PRIVATE_KEY="sec_test_xxx"
  • NEXT_PUBLIC_CAKEAUTH_PUBLIC_KEY: your public key
  • CAKEAUTH_PRIVATE_KEY: your private key

Don't know where to get those? Check out this quick cheat sheet.

Add CakeAuth middleware

Add CakeAuth middleware to your Next.js app:

In your src/middleware.ts file, add the following:

src/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)(.*)",
  ],
};

Add ready-to-use components

Add CakeAuth middleware to your Next.js app:

  1. Add CakeAuthProvider to your layout file
src/app/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>
  );
}
  1. Add authentication components to your page
src/app/page.tsx
import {
  PasswordReset,
  SignedIn,
  SignedOut,
  SignIn,
  SignUp,
  UserButton,
} from "@cakeauth/nextjs-app";
 
const Home = () => {
  return (
    <>
      <SignedOut>
        <SignIn />
        <SignUp />
        <PasswordReset />
      </SignedOut>
      <SignedIn>
        <UserButton />
      </SignedIn>
    </>
  );
};
 
export default Home;

Let's run it 🚀

npm run dev

Open your browser at http://localhost:3000 and you should be able to signup!

What's next?

TODO:

  • Add more auth options
  • protect pages/components
  • protect API routes
  • session management
  • more on sdk reference

Last updated on

On this page