The <hanko-auth> web component adds a login interface to your app. Begin by importing the register function from @teamhanko/hanko-elements into your Next.js component. Call it with the Hanko API URL as an argument to register <hanko-auth> with the browser’s CustomElementRegistry. Once done, include it in your JSX.
The Hanko client from @teamhanko/hanko-elements allows you to subscribe to specific events. For instance, the onSessionCreated event here triggers when a user successfully logs in. You can use this event to perform any desired action.
components/HankoAuth.tsx
"use client";import{ useEffect, useCallback, useState }from"react";import{ useRouter }from"next/navigation";import{ register,Hanko}from"@teamhanko/hanko-elements";const hankoApi = process.env.NEXT_PUBLIC_HANKO_API_URL;exportdefaultfunctionHankoAuth(){const router =useRouter();const[hanko, setHanko]= useState<Hanko>();useEffect(()=>setHanko(newHanko(hankoApi)),[]);const redirectAfterLogin =useCallback(()=>{// successfully logged in, redirect to a page in your application router.replace("/dashboard");},[router]);useEffect(()=> hanko?.onSessionCreated(()=>{redirectAfterLogin();}),[hanko, redirectAfterLogin]);useEffect(()=>{register(hankoApi).catch((error)=>{// handle error});},[]);return<hanko-auth/>;}
Now simply import the component you just created (HankoAuth)
To add JWT verification middleware with Hanko in your Next.js application, we’re using jose library. However, you’re free to choose any other suitable library. This middleware will ensure secure access to specific routes, like /dashboard here, by checking for valid JWT. Here we define the Hanko API URL, extract and verify the JWT from cookies, and redirect unauthorized users to the login page.
We will create two custom hooks to fetch the current user’s data and session data using @teamhanko/hanko-elements. The useUserData hook leverages the hanko.user.getCurrent() method to retrieve the currently logged-in user’s data.
On the other hand, the useSessionData hook uses the hanko.session.isValid() and hanko.session.get() methods to validate and fetch the current session data.