DEV Community

Manish Kr Prasad
Manish Kr Prasad

Posted on

Introducing Hanko: the open-source alternative to clerk

In the world of authentication management, Clerk has been a popular choice for many developers. However, with the rise of open-source alternatives, Hanko has emerged as a strong contender in the market. In this blog, we will explore Hanko, its features, and how it provides easy authentication management.

What is Hanko?
Hanko is an open-source authentication management platform that allows developers to easily manage user authentication and authorization. It provides a simple and secure way to handle user identities, making it an ideal choice for developers who want to focus on building their applications without worrying about authentication complexities.

Benefits of Using Hanko

  • Open-source: Hanko is open-source, which means that developers can customize and extend the platform to fit their needs.

  • Easy to use: Hanko provides a simple and intuitive API that makes it easy to manage user authentication.

  • Secure: Hanko provides enterprise-grade security features, including encryption and access controls.

  • Customizable: Hanko allows developers to customize the authentication experience to fit their application's needs.

Easy Authentication Management with Hanko

We will demonstrate how to create fully functional login and sign up functionality using Hanko's authentication management in a React application, including the implementation of cookie management.

First, you need to signup on Hanko Cloud . Don't worry there is already a youtube video available you can follow that to set up your account, here is the link Hanko Cloud setup.After the setup, you will have your API URL we will need that soon.

Now let's integrate hanko into our React App, assuming you have set up your React project.Let's follow the steps:

1. Install @teamhanko/hanko-elements:

Once you’ve initialized your React app, installing hanko-elements provides you with access to the prebuilt components: hanko-auth and hanko-profile.

npm install @teamhanko/hanko-elements
OR
yarn add @teamhanko/hanko-elements

2. Add the Hanko API URL:

Now add the API URL which you got while setting the Hanko Cloud, in your .env file.
REACT_APP_HANKO_API_URL=https://f4****-4802-49ad-8e0b-3d3****ab32.hanko.io

Let's create a React component Login which will handle the functionality of both login and signup.

import { useCallback, useEffect, useMemo } from "react";
import { Hanko, register } from "@teamhanko/hanko-elements";
import { useNavigate } from "react-router-dom";
import { hankoApi } from "./constants";

function Login() {

    const hanko = useMemo(() => new Hanko(hankoApi), []);
    const navigate = useNavigate();
    const defaultOptions = {
      cookieDomain: undefined,
      cookieSameSite: "none", // Specify whether/when cookies are sent with cross-site requests.
    };

    const redirectAfterLogin = useCallback(() => {
        navigate("/todos");
      }, [navigate]);

    useEffect(
        () =>
          hanko.onSessionCreated(() => {
            redirectAfterLogin();
          }),
        [hanko, redirectAfterLogin]
      );

    useEffect(() => {
      const registerHanko = async () => {
        try {
          await register(hankoApi, defaultOptions);
        } catch (error) {
          // handle error
          console.error("Error: ", error);
        }
      };

      registerHanko();
      }, []);

    return (
        <div  className=" flex justify-center">
            <hanko-auth />
        </div>
    )
}

export default Login
Enter fullscreen mode Exit fullscreen mode

With this code, your login and signup functionality is fully functional with cookies and session. Yes, that is all we need to do everything else will be handled by hanko.

Verifying the token in hanko
We have written an authMiddleware which is in Nodejs(Express) which checks if the user is an authenticated user or not so that you will be able to protect your routes.

import { NextFunction, Request, Response } from "express";
import * as jose from "jose"
import dotenv from 'dotenv'


dotenv.config()

const JWKS = jose.createRemoteJWKSet(
    new URL(`${process.env.HANKO_API_URL}/.well-known/jwks.json`)
  );

export default async function authMiddleware(req: Request, res: Response, next: NextFunction) {
  try {
    let token = req.cookies.hanko
    console.log('Cookie: ', token, typeof(token))

    // Extracting the token
    if (req.cookies && req.cookies.hanko ) {
      token = req.cookies.hanko;
    } else if ( req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer" ) {
      token = req.headers.authorization.split(" ")[1];
    }

    if (token === null || (token && token.length === 0) ) {
      res.status(401).send("Unauthorized");
      return;
    }

    // Verifying the token
    let authError = false;
    await jose.jwtVerify(token, JWKS).catch((err) => {
      authError = true;
      console.log(err);
    });

    if (authError) {
      res.status(401).send("Authentication Token not valid");
      return;
    }
    next()
  } catch (error) {
    console.log("Error:", error)
  }

}
Enter fullscreen mode Exit fullscreen mode

Conclusion:
Hanko makes it easy for developers to manage user authentication and authorization.You can find more about the API by visiting .Whether you're building a new application or migrating from an existing authentication solution, Hanko is definitely worth considering.

Top comments (0)