DEV Community

Cover image for Tutorial: How to Integrate Passkeys into Node.js (Express)
vdelitz for Corbado

Posted on • Originally published at corbado.com

Tutorial: How to Integrate Passkeys into Node.js (Express)

In this tutorial, we will walk you through the steps needed to integrate passkeys into your Node.js (Express) application using the Corbado Node.js SDK. Passkeys are a secure and user-friendly authentication method, allowing you to create a passwordless experience for your users. This tutorial is designed for developers with a basic understanding of Node.js, Express, and frontend technologies.

Read the full tutorial here

Prerequisites

Before you start, ensure that you have Node.js and npm installed on your machine. You'll also need basic familiarity with HTML, CSS, and JavaScript/TypeScript.

Node.js Express PasskeysThe final passkey authentication component

Project Structure

Let's begin by discussing the structure of our Node.js (Express) project for implementing passkeys. Here's how the files are organized:

├── .env                              # Contains all environment variables
└── src
    ├── views                        
    |   └── pages
    |       ├── login.ejs             # The homepage / login page
    |       └── profile.ejs           # The profile page
    ├── app.ts                        # The main server file
    ├── authController.ts             # Responsible to retrieve profile information in backend
    └── routes.ts                     # The routes for our frontend pages
Enter fullscreen mode Exit fullscreen mode

Setting Up Your Node.js (Express) Project

1. Create Project Files

Start by creating a new directory for your project. Inside this directory, create a package.json and tsconfig.json file, and include the necessary content from the example provided in the Corbado repository.

2. Install Dependencies

Run the following command to install the required dependencies:

npm install
Enter fullscreen mode Exit fullscreen mode

Configuring Corbado Passkey Authentication

To integrate Corbado's passkey authentication into your project, follow these steps:

1. Create Your Corbado Account

Sign up on the Corbado developer panel and set up your project by following the project wizard. You'll configure the project name, environment, and other settings necessary for passkey authentication.

2. Project Setup

After creating your project, generate an API secret in the Corbado developer panel under Settings > Credentials > API secrets. You'll use this secret in your .env file:

PROJECT_ID=your-project-id 
API_SECRET=your-api-secret
Enter fullscreen mode Exit fullscreen mode

3. Install the Corbado SDK

If you haven't already, install the Corbado Node.js SDK:

npm install @corbado/node-sdk
Enter fullscreen mode Exit fullscreen mode

4. Initialize the SDK

In your authController.ts, initialize the SDK using your project ID and API secret:

import { Request, Response } from 'express';
import { SDK, Config } from '@corbado/node-sdk';
import { config as dotenvConfig } from 'dotenv';

dotenvConfig();

const projectID = process.env.PROJECT_ID;
const apiSecret = process.env.API_SECRET;

const cboConfig = new Config(projectID!, apiSecret!);
const sdk = new SDK(cboConfig);
Enter fullscreen mode Exit fullscreen mode

Creating Routes and Views

1. Set Up Routes

Define your routes in routes.ts to serve the login and profile pages:

import express from 'express';
import { auth, profile } from './authController';

const router = express.Router();

router.get('/', auth);
router.get('/profile', profile);

export default router;
Enter fullscreen mode Exit fullscreen mode

2. Set Up Node.js (Express) Backend

Now, we add two API routes in src/authController.ts delivering HTML to the client.
The homepage / login page is static while the profile route will provide user information to our template which is retrieved via the Corbado Node.js SDK from the short_term_session cookie (represented as JWT).

export function auth(req: Request, res: Response) {
    res.render('pages/login')
}


export async function profile(req: Request, res: Response) {
    const shortSession = req.cookies.cbo_short_session
    if (!shortSession) {
        res.redirect("/")
    }
    try {
        const user = await sdk.sessions().getCurrentUser(shortSession)
        const cboId = user.getID()
        const email = user.getEmail()
        const dbUser = await findById(cboId)
        if (!dbUser) {
            throw Error("This user doesn't exist")
        }
        res.render('pages/profile', {cboId, email})
    } catch (e) {
        console.log(e)
        res.redirect("/")
    }
}
Enter fullscreen mode Exit fullscreen mode

Put everything together in our app.ts file.
We initialize our Node.js (Express) app, use cookieParser to get access to cookie headers, set our template rendering engine to ejs and define our application's port.

import express from 'express';
import {config as dotenvConfig} from "dotenv";
import cookieParser from "cookie-parser";
import authRoutes from "./routes"
import {sequelize} from "../models";

dotenvConfig()

const app = express();
app.use(cookieParser())

app.set('views', './src/views')
app.set('view engine', 'ejs');

const port = 3000;
Enter fullscreen mode Exit fullscreen mode

3. Login Page

In login.ejs, load the Corbado authentication UI component:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://unpkg.com/@corbado/web-js@2.9.0/dist/bundle/index.css"/>
    <script src="https://unpkg.com/@corbado/web-js@2.9.0/dist/bundle/index.js"></script>
</head>
<body>
<div id="corbado-auth"></div>
<script type="module">
    await Corbado.load({
        projectId: "<%= process.env.PROJECT_ID %>",
        setShortSessionCookie: true
    });

    async function onLoggedIn() {
        window.location.href = "/profile";
    }

    const authElement = document.getElementById('corbado-auth');
    Corbado.mountAuthUI(authElement, {
        onLoggedIn: onLoggedIn,
    });
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

4. Profile Page

In profile.ejs, display the user's profile information and provide a logout button:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://unpkg.com/@corbado/web-js@2.9.0/dist/bundle/index.css"/>
    <script src="https://unpkg.com/@corbado/web-js@2.9.0/dist/bundle/index.js"></script>
</head>
<body>
<div>
    <h1>User profile:</h1>
    <p>Email: <%= email %></p>
    <p>Name: <%= cboId %></p>
    <button id="logoutButton">Logout</button>
</div>

<script type="module">
    await Corbado.load({
        projectId: "<%= process.env.PROJECT_ID %>",
        setShortSessionCookie: true
    });

    document.getElementById("logoutButton").addEventListener("click", async () => {
        await Corbado.logout();
        window.location.href = "/";
    });
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Running the Application

Start your application using the command:

npm run start
Enter fullscreen mode Exit fullscreen mode

Access your app at http://localhost:3000, sign up, and check out the profile page at /profile.

Conclusion

By following this guide, you've successfully added passkey authentication to your Node.js (Express) application using Corbado. This not only enhances security but also provides a seamless user experience without the need for traditional passwords. If you'd like to explore more features, check out Corbado's session management and other tools in their official documentation or have a look at the original blog post.

Top comments (0)