For best results we recommend using the App Router.
Installation
Create or modify your .env.local file with the following:
Next we’ll want to add session capabilities to our app.
Adding Secure Sessions
Our recommendation is to use the iron-session package to add secure sessions to your Next.js app. We’ll also use the server-only package as extra assurance we aren’t leaking sensitive information to the client.
Start by installing it by running the following command:
Then create a new file named lib/session.ts:
We’ll be storing the currently logged in Account ID and WebAuth challenge. The information will be persisted using Next.js cookie primitives. Next, we can begin working on our registration system.
Account Sign Ups
In order to create a new WebAuthn credential we’ll need to generate a challenge to use. Start by creating a new file named actions/challenge.ts with the following:
We are generating a random sequence of bytes and storing it in a secure session to read from later.
Next let’s build the register webpage. We’ll be building a server rendered page that mounts a client component form. Create a new file named app/register/page.tsx with the following:
The RegisterForm component is more complex. We’ll want to prompt the user for an email, a username, and then have a form submit handler.
Finally we’ll create the registration action we referenced in the form. Create a new file named actions/register.ts:
Here we will check to see if a user is logged in (and prevent a new registration if they are), validate the input data, and then call 0x57 to create a new Account. If the result is successful, we will save their new ID in the session (logging them in) and redirect them to a protected page.
Adding Account Sign Out
Logging a user out of your service is incredibly easy with Next.js route handlers. You can create a new file named app/logout/route.ts and export a GET request handler:
We destroy the current session and redirect the user to the homepage.
Creating Account Sign In
The final piece is adding a login page. The structure will be similar to the registration flow - we’ll create a server component page, a client component form, and then an action form submission handler.
Start by creating a new file named app/login/page.tsx:
Next, create a new file named app/login/LoginForm.tsx:
We don’t need to prompt for a username or email because WebAuthn counts as the entire login mechanism! The final piece is creating the submission handler. Create a new file named /actions/login.ts:
This action is almost exactly the same as the registration handler. The key difference is instead of calling the registration 0x57 API we’re calling the session API via hex57.login!
Requiring Users be Logged In
You can require users be logged in by checking the session value - no need to call 0x57 APIs!
Adding a Profile Page
If you want to display additional information about the logged in user, you can call the 0x57 API like this: