DEV Community

Cover image for How to add Authentication with HANKO in your project? ✨✨✨
Ankur Singh
Ankur Singh

Posted on • Updated on

How to add Authentication with HANKO in your project? ✨✨✨

Welcome πŸ‘‹ to this blog. In this blog we will learn how to integrate Hanko Authentication within your application. In this blog, I am using the Image project whose code can be found here.

File Structure of the repository 🀩

This is the ReactJS project created with

project-directory/
β”‚
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ favicon.ico
β”‚   β”œβ”€β”€ index.html
β”‚   β”œβ”€β”€ logo192.png
β”‚   β”œβ”€β”€ logo512.png
β”‚   β”œβ”€β”€ manifest.json
β”‚   β”œβ”€β”€ robots.txt
β”‚
β”œβ”€β”€ src/
β”‚   β”‚
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ HankoAuth.jsx
β”‚   β”‚   β”œβ”€β”€ Header.jsx
β”‚   β”‚   β”œβ”€β”€ Hero.jsx
β”‚   β”‚   β”œβ”€β”€ HighlightTextHero.jsx
β”‚   β”‚   β”œβ”€β”€ List.jsx
β”‚   β”‚   β”œβ”€β”€ MainDrawer.jsx
β”‚   β”‚
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ config.js
β”‚   β”‚
β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”œβ”€β”€ AboutUsPage.jsx
β”‚   β”‚   β”œβ”€β”€ AuthPage.jsx
β”‚   β”‚   β”œβ”€β”€ ContactUsPage.jsx
β”‚   β”‚   β”œβ”€β”€ HelpAndSupport.jsx
β”‚   β”‚   β”œβ”€β”€ IndexPage.jsx
β”‚   β”‚
β”‚   ...
...
Enter fullscreen mode Exit fullscreen mode

App.jsx πŸ˜„

This is the App.jsx code.

import './App.css';
import { ChakraProvider } from '@chakra-ui/react'
import IndexPage from './pages/IndexPage';
import AboutUsPage from './pages/AboutUsPage';
import HelpAndSupport from './pages/HelpAndSupport';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ContactUsPage from './pages/ContactUsPage';
import List from './components/List';

function App() {
  return (
    <ChakraProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<IndexPage />} />
          <Route path="/help&support" element={<HelpAndSupport />} />
          <Route path="/aboutus" element={<AboutUsPage />} />
          <Route path="/contactus" element={<ContactUsPage />} />
          <Route path="/list" element={<List />} />
        </Routes>
      </BrowserRouter>
    </ChakraProvider>
  )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

To create an Authentication component we have HankoAuth.jsx

The code is as follows 🀩

import { useEffect } from "react";
import { register } from "@teamhanko/hanko-elements";
import { useNavigate } from "react-router-dom";
const hankoApi = process.env.REACT_APP_KEY;


export default function HankoAuth() {
  const navigate = useNavigate();
  useEffect(() => {
    register(hankoApi)
    .catch((error) => {
      // handle error
    })
    .then((registration) => {
      // handle registration
      navigate("/");
    });
  }, []);

  return (
    <div className="flex min-h-screen justify-center items-center">
      <hanko-auth/>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

You can get your hankoApi by login to the cloud console of Hanko.

Time to integrate within your app πŸ˜„

Here is the code of the IndexPage or MainPage.

import React, { useState, useEffect } from "react";
import MainDrawer from "../components/MainDrawer";
import Hero from "../components/Hero";
import Header from "../components/Header";
import HankoAuth from "../components/HankoAuth";
import userId from "../config/config.js"

function IndexPage() {
    const [user, setUser] = useState(null);
    useEffect(() => {
        if (userId !== null) {
            setUser(userId);
        }
    }, [userId]);
    return (
        <>
            <Header setUser={setUser} />
            {!user && <HankoAuth />}
            {user && <>
                <MainDrawer />
                <Hero />
            </>}

        </>
    )
}

export default IndexPage;
Enter fullscreen mode Exit fullscreen mode

These code blocks are mainly responsible for the conditional rendering of the auth components.

        {!user && <HankoAuth />}
            {user && <>
                <MainDrawer />
                <Hero />
         </>}
Enter fullscreen mode Exit fullscreen mode

How to get the data of logged-in user πŸ€—

This logic is implemented in config.js. We can fetch the data of the user using the SDK.
Read More

import { Hanko } from "@teamhanko/hanko-elements";

let userId = null;
const hankoApi = process.env.REACT_APP_KEY;
const hanko = new Hanko(hankoApi);

try {
    const { id } = await hanko.user.getCurrent();
    if (id) {
        userId = id;
    }
} catch (error) {
    console.error('Error occurred while fetching user data:', error);
}

export default userId;
Enter fullscreen mode Exit fullscreen mode

This is how we can intergrate the Hanko Auth within our web application. πŸ€—πŸ€—πŸ€—

You got it 🀩

You have learned how to integrate Hanko Auth into your web application. Thanks for reading till the end. If you have any feedback, the comment section is yours. If you find this blog useful you can start this repository and connect with me.

Hire me: ankursingh91002@gmail.com
LinkedIn
Twitter

Top comments (0)