How to add Authentication with HANKO in your project? ✨✨✨
Published: 2023-10-24 14:50:51

Welcome 👋 to this blog. In this blog we will learn how to integrate [Hanko](https://www.hanko.io/) Authentication within your application. In this blog, I am using the Image project whose code can be found [here](https://github.com/ankur0904/Hanko-Hackthon).

## File Structure of the repository 🤩

> This is the `ReactJS` project created with 
- [Hanko Auth](https://www.hanko.io/)
- [Chakra-UI](https://chakra-ui.com/)
- [Supabase](https://supabase.com/)

```
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
│   │
│   ...
...
```

## App.jsx 😄

This is the `App.jsx` code. 

```jsx
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;
```

## To create an Authentication component we have `HankoAuth.jsx` 
The code is as follows 🤩
```js
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>
  );
}
```

> You can get your `hankoApi` by login to the cloud console of [Hanko](https://www.hanko.io/).


## Time to integrate within your app 😄

Here is the code of the `IndexPage` or `MainPage`.
```js
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;
```
These code blocks are mainly responsible for the conditional rendering of the auth components.
```js
        {!user && <HankoAuth />}
            {user && <>
                <MainDrawer />
                <Hero />
         </>}
```

## 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](https://docs.hanko.io/guides/users/get-user-data)

```js
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;
```

*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](https://github.com/ankur0904/Hanko-Hackthon/tree/main) repository and connect with me.

Hire me: ankursingh91002@gmail.com
[LinkedIn](https://www.linkedin.com/in/ankur-singh-161458227/)
[Twitter](https://twitter.com/ankursingh91002)