Implementing Hanko Authentication in Next.js
Tech Stack: Next.js, TypeScript, Hanko, Hanko v2
Implementing Hanko Authentication in Next.js
During my recent exploration of modern authentication methods for my Next.js application, I discovered Hanko - a passwordless authentication solution that leverages passkeys. The implementation process was surprisingly straightforward, and the benefits for both developers and users have been significant. Here's my experience integrating Hanko into my Next.js project, including the recent migration to Hanko v2 with enhanced features.
1. Why I Chose Hanko for Authentication
After researching various authentication options, I was drawn to Hanko for several reasons:
- Passwordless Authentication: No more managing password hashing, storage, or reset flows
- Passkey Support: Leveraging the latest FIDO2 standards for secure, phishing-resistant authentication
- Simple Integration: Pre-built components that required minimal configuration
- Developer Experience: Clean API and comprehensive documentation
- User Experience: Smooth, modern authentication flow that works across devices
The promise of eliminating password-related headaches while improving security was too good to pass up.
2. Setting Up Hanko Cloud
Getting started with Hanko was straightforward:
# First, I installed the Hanko Elements package
npm install @teamhanko/hanko-elements
Then I created a Hanko Cloud account and set up a new project:
- Signed up at cloud.hanko.io
- Created a new organization and project
- Set my application URL to match my development environment
- Enabled email and passkey authentication methods
- Copied the API URL for my environment configuration
The Hanko Cloud dashboard provided a clear interface for managing authentication settings, and I appreciated the ability to configure different projects for development and production environments.
3. Implementing the Authentication Component
The core of the implementation was creating a reusable HankoAuth component:
/**
* HankoAuth Component
*
* A client-side authentication component that integrates Hanko authentication service.
* This component handles user authentication flows and redirects using Hanko Elements.
*/
"use client";
import { useEffect, useCallback, useState } from "react";
import { useRouter } from "next/navigation";
import { register, Hanko } from "@teamhanko/hanko-elements";
export default function HankoAuth() {
const router = useRouter();
const [hanko, setHanko] = useState<Hanko>();
useEffect(() => {
// Get the API URL from environment variable
const hankoApi = process.env.NEXT_PUBLIC_HANKO_API_URL;
if (!hankoApi) {
console.error("Hanko API URL not found");
return;
}
setHanko(new Hanko(hankoApi));
// Register Hanko elements
register(hankoApi).catch((error) => {
console.error("Failed to register Hanko:", error);
});
}, []);
const redirectAfterLogin = useCallback(() => {
router.replace("/admin");
}, [router]);
useEffect(
() =>
hanko?.onSessionCreated(() => {
redirectAfterLogin();
}),
[hanko, redirectAfterLogin]
);
return <hanko-auth />;
}
I was pleasantly surprised by how little code was needed. The hanko-auth web component handled all the UI and authentication logic, while I just needed to configure the redirect after successful login.
4. Creating the Login Page
With the HankoAuth component ready, creating a login page was trivial:
"use client";
import HankoAuth from "@/app/components/HankoAuth";
export default function LoginPage() {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="p-8 bg-white rounded-lg shadow-md w-full max-w-md">
<h1 className="text-2xl font-bold mb-6 text-center">Login</h1>
<HankoAuth />
</div>
</div>
);
}
The simplicity of this implementation was refreshing compared to traditional authentication systems that require extensive form handling, validation, and error management.
5. Securing Routes with Middleware
To protect certain routes in my application, I implemented middleware that verifies the Hanko JWT token:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import * as jose from "jose";
export async function middleware(request: NextRequest) {
const hankoApiUrl = process.env.NEXT_PUBLIC_HANKO_API_URL;
if (!hankoApiUrl) {
console.error("Hanko API URL not found");
return NextResponse.redirect(new URL("/login", request.url));
}
// Only protect /admin routes
if (!request.nextUrl.pathname.startsWith("/admin")) {
return NextResponse.next();
}
try {
// Get the JWT from the cookie
const hankoJwt = request.cookies.get("hanko")?.value;
if (!hankoJwt) {
return NextResponse.redirect(new URL("/login", request.url));
}
// Fetch JWKS from Hanko API
const jwks = jose.createRemoteJWKSet(
new URL("/.well-known/jwks.json", hankoApiUrl)
);
try {
// Verify the JWT
const verifiedJWT = await jose.jwtVerify(hankoJwt, jwks);
if (!verifiedJWT) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
} catch (e) {
// Invalid JWT
return NextResponse.redirect(new URL("/login", request.url));
}
} catch (e) {
console.error("Auth error:", e);
return NextResponse.redirect(new URL("/login", request.url));
}
}
// Configure the middleware to run only for /admin routes
export const config = {
matcher: "/admin/:path*",
};
This middleware intercepts requests to protected routes, verifies the JWT token using the Hanko JWKS endpoint, and redirects unauthenticated users to the login page.
6. User Profile Management
For user profile management, I created a HankoProfile component:
"use client";
import { useEffect, useState } from "react";
import { Hanko } from "@teamhanko/hanko-elements";
import { register } from "@teamhanko/hanko-elements";
export default function HankoProfile() {
const [hanko, setHanko] = useState<Hanko>();
useEffect(() => {
const hankoApi = process.env.NEXT_PUBLIC_HANKO_API_URL;
if (!hankoApi) {
console.error("Hanko API URL not found");
return;
}
let unregister: (() => void) | undefined;
const init = async () => {
try {
setHanko(new Hanko(hankoApi));
unregister = await register(hankoApi);
} catch (error) {
console.error("Error initializing Hanko:", error);
}
};
init();
return () => {
try {
if (typeof unregister === 'function') {
unregister();
}
} catch (error) {
console.error("Error during cleanup:", error);
}
};
}, []);
if (!hanko) {
return null;
}
return <hanko-profile />;
}
This component allows users to manage their email addresses and passkeys, all handled by the hanko-profile web component.
7. The User Experience
From a user perspective, the authentication flow is remarkably smooth:
- First-time users: Enter email → Receive a one-time passcode → Register a passkey
- Returning users: Use passkey (biometric authentication) → Instantly authenticated
The passkey experience is particularly impressive - users can authenticate with a fingerprint, face scan, or device PIN, depending on their device capabilities. No passwords to remember, no credentials to steal.
8. Development and Production Setup
One aspect I appreciated was the clear separation between development and production environments:
-
Development:
- Created a development project in Hanko Cloud
- Set App URL to
http://localhost:3000 - Added API URL to
.env.local
-
Production:
- Created a separate production project
- Set App URL to my production domain
- Added API URL to Vercel environment variables
This separation allowed me to test thoroughly in development without affecting production users.
9. Benefits of Passkey Authentication
After implementing Hanko, I've observed several benefits:
- Enhanced Security: Passkeys are phishing-resistant and eliminate password-related vulnerabilities
- Improved User Experience: No more password resets or complex password requirements
- Reduced Development Effort: No need to build and maintain password management systems
- Cross-Device Compatibility: Works seamlessly across devices and platforms
- Future-Proof: Aligned with the industry movement toward passwordless authentication
10. Challenges and Solutions
While the implementation was mostly smooth, I did encounter a few challenges:
- Browser Compatibility: Some older browsers don't support WebAuthn/passkeys yet. Hanko gracefully falls back to email OTP authentication in these cases.
- User Education: Some users were unfamiliar with passkeys. I added brief explanations to guide them through the process.
- Testing: Testing authentication flows required multiple devices and browsers. I created a comprehensive testing plan to ensure everything worked as expected.
Conclusion
Implementing Hanko authentication in my Next.js application has been a positive experience. The simplicity of the integration, combined with the security and usability benefits of passkeys, has made it a worthwhile investment.
If you're building a Next.js application and looking for a modern authentication solution, I highly recommend giving Hanko a try. The days of password-related headaches might finally be behind us!
For more information, check out the official Hanko documentation and their Next.js starter repository.