Logo

dev-resources.site

for different kinds of informations.

Tutorial: How to Integrate Passkeys into Next.js

Published at
8/26/2024
Categories
nextjs
react
authentication
passkeys
Author
vdelitz
Author
7 person written this
vdelitz
open
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.

passkeys Article's
30 articles in total
Favicon
Ensuring Successful Passkey Deployment: Testing Strategies for Enterprises
Favicon
How to integrate Passkeys into Enterprise Stacks?
Favicon
Initial Planning & Technical Assessment for Passkeys
Favicon
How to build a Passkey Product, a Strategy and Design for it?
Favicon
How to Engage with Stakeholders in Passkey Projects?
Favicon
Update / Delete Passkeys via WebAuthn Signal API
Favicon
Introduction to Smart Wallets and Passkeys authentication
Favicon
Passkeys, Are passwords obsolete now?!
Favicon
Guide: How to Add Passkeys to Enterprise Systems
Favicon
No Matching Passkeys Available: Troubleshooting Your Login Issue
Favicon
How to Activate Apple Passkeys onΒ MacBooks
Favicon
How to Activate Microsoft Passkeys on Windows
Favicon
How to Use Passkeys with Google Password Manager
Favicon
How to Verify User Accounts in Passkey-Based Systems
Favicon
Passkey One-Tap Login: The Most Efficient Login
Favicon
User Presence & Verification in WebAuthn: Detailed Guide
Favicon
Let's Make the Internet a Safer Place! State of Passkeys is Now Live on Product Hunt πŸš€
Favicon
Payment Passkeys @ Mastercard: Revolution for PaymentΒ Security
Favicon
How to Integrate Passkeys in Python (FastAPI)
Favicon
Tutorial: Integrate Passkeys into Django (Python)
Favicon
Tutorial: How to Integrate Passkeys into Next.js
Favicon
Passkeys / WebAuthn Library v2.0 is there! πŸŽ‰
Favicon
WebAuthn PRF Extension, Related Origins & Passkey Upgrades
Favicon
How To Activate Apple Passkeys onΒ iPhones
Favicon
Passkeys in Australia: Download Free Whitepaper
Favicon
Why B2C Auth is Fundamentally Broken
Favicon
Why B2C Auth is Fundamentally Broken
Favicon
WebAuthn & iframes Integration for Cross-Origin Authentication
Favicon
How Passkeys Protect Against Phishing
Favicon
Are Device-Bound Passkeys AAL2- or AAL3-Compliant?

Featured ones: