DEV Community

Cover image for Easy Authentication Using Hanko.io
Istaprasad Patra
Istaprasad Patra

Posted on

Easy Authentication Using Hanko.io

Building dependable online apps in the rapidly changing world of web development today requires smooth and secure authentication. A contemporary, safe, and passwordless method of user authentication is provided by Hanko, a robust authentication API. I'll demonstrate how to integrate Hanko Elements and Hanko API into a React application in this blog post, and then I'll show you a demonstration of the authentication system we created.

Let's get started!

What is Hanko?

Hanko is an authentication service that offers a passwordless experience to streamline the user authentication process. Because it supports WebAuthn, developers may use security keys, biometrics, or other passwordless login methods. Additionally, Hanko offers pre-made user interface components (known as Hanko Elements) to facilitate a smooth integration process.

Step 1: Setting Up Your React Application

First, if you haven’t already, initialize a React application using the following commands:

npx create-react-app hanko
cd hanko
npm install react-router-dom
npm start
Enter fullscreen mode Exit fullscreen mode

This will create a new React project and spin up the development server.

Step 2: Install Hanko Elements

Next, install the Hanko Elements library to get access to their pre-built authentication components:

npm install @teamhanko/hanko-elements
Enter fullscreen mode Exit fullscreen mode

This package will allow us to easily embed Hanko authentication elements into our React components.

Step 3: Configure Hanko in Your Application

Before diving into the code, you’ll need to sign up at Hanko.io and get your API key. After setting up your Hanko project, you can retrieve the Hanko API base URL and Hanko API key from your dashboard.

Add these values to your environment variables in the .env file:

REACT_APP_HANKO_API_URL=<YOUR_HANKO_API_BASE_URL>
REACT_APP_HANKO_API_KEY=<YOUR_HANKO_API_KEY>
Enter fullscreen mode Exit fullscreen mode

Step 4: Building the Authentication Flow

Now that we have the project set up and the Hanko Elements installed, let's move on to integrating the authentication functionality.

Create a Login.js file that will handle user authentication:

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

const hankoApi = process.env.REACT_APP_HANKO_API_URL;

function Login() {
  const navigate = useNavigate();
  const hanko = useMemo(() => new Hanko(hankoApi), []);
  const [userState, setUserState] = useState({
    id: "",
    email: "",
    error: "",
  });

  const [sessionState, setSessionState] = useState({
    userID: "",
    jwt: "",
    isValid: false,
    error: "",
  });

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

  useEffect(
    () =>
      hanko.onSessionCreated(() => {
        hanko?.user
          .getCurrent()
          .then(({ id, email }) => {
            setUserState({ id, email, error: "" });
            console.log(id,email)
          })
          .catch((error) => {
            setUserState((prevState) => ({ ...prevState, error: error }));
          });
        redirectAfterLogin();
      }),
    [hanko, redirectAfterLogin]
  );

  useEffect(() => {
    if (hanko) {
      const isValid = hanko.session.isValid();
      const session = hanko.session.get();

      if (isValid && session) {
        const { userID, jwt = "" } = session;
        setSessionState({
          userID,
          jwt,
          isValid,
          error: null,
        });
        console.log(jwt);
      } else {
        setSessionState((prevState) => ({
          ...prevState,
          isValid: false,
          error: "Invalid session",
        }));
      }
    }
  }, [hanko]);

  useEffect(() => {
    register(hankoApi).catch((error) => {
      console.log(error);
    });
  }, []);
  return (
    <div className="m-0 flex justify-center items-center">
      <hanko-auth />
    </div>
  );
}

export default Login;
Enter fullscreen mode Exit fullscreen mode

In the above code, we authenticate without even using an backend server, simply using hanko.io . The provides a frontend block which helps the user to login and also signin it he/she doesn't has an account. It authenticates does email verfication by sending OTP to the user's email. It also provides the feature of login even if the user forgets his password and also provides 2-factor authentication using passkeys and also using device's biometrics .You can also other social authentication methods like google,facebook,github etc.

Here, we also get jwt tokens which can be further used in other routes to check the user's autheticity using the JWKS URL. We will be able to do all these stuff without even having a backend server.

Step 7: Handling Logout

To allow users to log out, we can just add a logout button in the further pages of the website.

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Hanko } from "@teamhanko/hanko-elements";

const hankoApi = process.env.REACT_APP_HANKO_API_URL;

function Logout() {
    const navigate = useNavigate();
    const [hanko, setHanko] = useState(<Hanko />);

    useEffect(() => {
      import("@teamhanko/hanko-elements").then(({ Hanko }) =>
        setHanko(new Hanko(hankoApi ?? ""))
      );
    }, []);

    const logout = async () => {
      try {
        await hanko?.user.logout();
        navigate("/");
      } catch (error) {
        console.error("Error during logout:", error);
      }
    };

    return (
    <button onClick={logout} className="mt-10 bg-red-50 w-24 text-2xl hover:text-3xl hover:text-red-400 duration-300">Logout</button>
);
}

export default Logout
Enter fullscreen mode Exit fullscreen mode

This is just an example how you can use the logout component in your website. As you can see that we can logout easily just using simple functions.

My Experience

I personally loved hanko.io because first of all, it has made my work very easy and also when I read the docs, it is super easy to understand and use. Most of the code which will be used in development process is already mentioned in the docs and so it makes our work very easy.

Secondly, there are a lot of options to use it like we can use it with other frontend frameworks like Vue, Angular, Svelte etc. We can also with many languages with which backend servers are written like NodeJs, Go, Python, Rust etc. So this makes it very compatible with every language. We can also use it with other frameworks like NextJs, Remix, Nuxt etc.

When I first visited their website, I found it to be very professional and easy to navigate. If someone just follows it step by step then it is super easy to understand and use.

With this blog, developers can understand how to integrate a modern and secure authentication system using Hanko in their projects, ensuring robust security while enhancing the user experience.

For more information you can visit hanko.io

Top comments (0)