DEV Community

Cover image for Tutorial: How to Integrate Passkeys into Next.js
vdelitz for Corbado

Posted on • Originally published at corbado.com

Tutorial: How to Integrate Passkeys into Next.js

Overview

In this tutorial, we'll walk through the process of integrating passkeys into a Next.js application using Corbado. You'll learn how to set up passkey-first authentication and manage user sessions, providing a secure and seamless login experience for your users.

View full blog post here

Prerequisites

Before diving into the implementation, ensure you have a basic understanding of Next.js, HTML, CSS, and JavaScript/TypeScript. You should also have Node.js and NPM installed on your system.

Passkeys Next.jsThe final passkey authentication page in Next.js

Project Structure

Our example Next.js passkey project is structured as follows:

next.js/
├── app/
│ ├── auth/
│ │ └── page.tsx
│ ├── profile/
│ │ └── page.tsx
│ ├── user-data/
│ │ └── route.ts
│ ├── globals.css
│ ├── layout.tsx
│ ├── page.tsx
│ └── _utils/
│   ├── LogoutButton.tsx
│   ├── Provider.tsx
│   ├── QueryClientWrapper.tsx
│   └── nodeSdk.ts
└── .env.example
Enter fullscreen mode Exit fullscreen mode

This structure helps in organizing the different components and utilities needed for integrating passkeys.

Setting Up Your Next.js Project

To start, initialize a new Next.js project by running the following command in your terminal:

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

During setup, select the following options:

  • Project Name: passkeys-demo-nextjs
  • TypeScript: Yes
  • ESLint: Yes
  • Tailwind CSS: Yes
  • App Router: Yes

Once your project is set up, you can proceed with configuring passkey authentication.

Integrating Corbado Passkey Authentication

To implement passkeys in your Next.js project, follow these steps:

1. Set Up Your Corbado Account

First, create an account on the Corbado developer panel. The setup wizard will guide you through naming your project, selecting "Corbado Complete" as your product, and configuring the necessary environment settings.

2. Prepare Your Next.js Project

Install the required Corbado packages:

npm install @corbado/react @corbado/node-sdk
npm install --save-dev @corbado/types
Enter fullscreen mode Exit fullscreen mode

Create a wrapper around the <CorbadoProvider/> component to manage client-side rendering:

"use client";

import { CorbadoProvider } from "@corbado/react";

export default function Provider({ children }) {
  return (
    <CorbadoProvider
      projectId={process.env.NEXT_PUBLIC_CORBADO_PROJECT_ID!}
      darkMode="off"
      setShortSessionCookie={true}
    >
      {children}
    </CorbadoProvider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Integrate the provider wrapper into your root layout

import "./globals.css"
import type {Metadata} from "next"
import {Inter} from "next/font/google"
import CorbadoProvider from "./_utils/Provider"

const inter = Inter({subsets: ["latin"]})

export const metadata: Metadata = {
    title: "Next Corbado Example",
    description: "Go passwordless with Corbado and Next.js",
}

export default function RootLayout({ children, }: { children: React.ReactNode }) {
    return (
        <html lang='en'>
        <CorbadoProvider>
            <body className={inter.className}>{children}</body>
        </CorbadoProvider>
        </html>
    )
}
Enter fullscreen mode Exit fullscreen mode

3. Build the Authentication Page

In page.tsx, replace the default content with the <CorbadoAuth/> component, which handles user sign-ups and logins. Ensure the page renders on the client side by including the 'use client' directive.

'use client'

import { CorbadoAuth } from "@corbado/react"
import { useRouter } from "next/navigation"

export default function Auth() {

    const router = useRouter()
    const onLoggedIn = () => {
        router.push("/profile")
    }

    return (
        <div>
            <CorbadoAuth onLoggedIn={onLoggedIn} />
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

4. Configure Backend Authentication

Create a utility function in nodeSdk.ts to provide access to the Corbado Node.js SDK across your application:

import { Config, SDK } from "@corbado/node-sdk";

const projectID = process.env.NEXT_PUBLIC_CORBADO_PROJECT_ID!;
const apiSecret = process.env.CORBADO_API_SECRET!;

const config = new Config(projectID, apiSecret);
const sdk = new SDK(config);

export default function getNodeSDK() {
  return sdk;
}
Enter fullscreen mode Exit fullscreen mode

5. Create a Profile Page

Develop a profile page in profile/page.tsx to display user information. The page retrieves the cbo_short_session cookie, which is a JWT used for authentication. If the user is authenticated, their profile information will be displayed.

import {cookies} from "next/headers";
import getNodeSDK from "@/app/_utils/nodeSdk";
import {redirect} from "next/navigation";
import LogoutButton from "@/app/_utils/LogoutButton";
import PasskeyList from "@/app/_utils/PasskeyList";

// the user data will be retrieved server side
export default async function Profile() {
    const cookieStore = cookies();
    const session = cookieStore.get("cbo_short_session");
    if (!session) {
        return redirect("/");
    }
    const sdk = getNodeSDK();
    let user;
    try {
        user = await sdk.sessions().getCurrentUser(session.value);
        if (!user.isAuthenticated()) {
            throw Error;
        }
    } catch {
        return redirect("/");
    }
    return (
        <div>
            <h1>Profile Page</h1>
            <p>
                User-ID: {user.getID()}<br/>
                Email: {user.getEmail()}
            </p>
            <LogoutButton/>
            <PasskeyList/>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we also imported a <LogoutButton/> component which needs to be in another file as it utilizes onClick functionality to log the user out. Place this one inside app/_utils/LogoutButton.tsx.

6. Run the Application

Finally, run your Next.js application:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 to see your passkey implementation in action. Upon successful login, you will be redirected to the profile page.

Conclusion

This guide provided a step-by-step approach to implementing passkeys in a Next.js application using Corbado. By following these instructions, you can offer your users a secure and passwordless authentication experience. For more details on session management and passkey integration, refer to the Corbado documentation.

Top comments (0)