Authenticate nextjs application with hanko frontend auth.
Tags: webdev, javascript, frontend, hanko
Published: 2024-01-07 14:54:59

Hanko is a lightweight, open source user authentication solution that takes you on the journey beyond passwords.
**Integrate Hanko with Next.js**
Learn how to quickly add authentication and user profile in your Next.js app using Hanko.
First Create New Nextjs app

```
npx create-next-app@latest nextjs-blog --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter BLOGapp"
```
Now install hanko frontend-elements

```
yarn add @teamhanko/hanko-elements

```
now run development server

```
yarn dev
```


Now go to https://cloud.hanko.io and signup for api access.

> 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6saqz23t3c1kk8zak8b6.png)
enter suitable project name and in app url enter `http://localhost:3000` you can access hanko frontend elements from this url only.
Now create `.env` file in app directory and copy Hanko api url to .env file.

```
NEXT_PUBLIC_HANKO_API_URL = <Hanko api url from general setting>
```
Now go to supabase.com create a project and signup and create a project 
Now go to project setting and click database on right side 
Go to Nodejs and copy the database url and now add this in .env file

```
DATABASE_URL = postgresql://postgres:[YOUR-PASSWORD]@db.dshyzhthijimhivhaeyq.supabase.co:5432/postgres
```
Replace password with the password of the project that you entered during the creation of the project...
Now this a good to go.
Install prisma 

```
yarn add -d prisma
```
Finally, set up Prisma with the init command of the Prisma CLI:

```
yarn prisma init 
```
Now navigate to prisma folder and  open schema.prisma file 

Add this code top of schema file to connect with frontend provider of db client
```
generator client {
  provider = "prisma-client-js"
}
```
Now connect with postgresql database 

```
datasource db {
  provider     = "postgresql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}
```
Create model named user to store the login user in backend

```


model User {
  id    String @id @unique 
  email String @unique

}
```

Now run this command to migrate database.

```
yarn prisma migrate dev --name init

```
Now create a folder named db in src folder
In index.js copy and paste this code. Here we imported PrismaClient and setup the db for using in backend.

```
import { PrismaClient } from '@prisma/client'

declare global {
  // eslint-disable-next-line no-var
  var cachedPrisma: PrismaClient
}

let prisma: PrismaClient
if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient()
} else {
  if (!global.cachedPrisma) {
    global.cachedPrisma = new PrismaClient()
  }
  prisma = global.cachedPrisma
}

export const db = prisma
```

Now app/api/auth/route.ts. In order to serialize cookie we will use 

```
import { db } from "@/db";
import { serialize } from "cookie";




export  async function POST(request:Request) {
 
    // Handle the POST request here
    // You can access request data using req.body
    const data = await request.json();
    const {id,email} = data;
    if (!id || !email){
        return Response.json({
            message:"Missing Data in body",
            
        },{
            status:404
        })
    }

    const already_user = await db.user.findFirst({
      where:{
        id:id
      }
    })
    if (already_user)
    { 
      
      const ck = serialize("user_id",id,{
        secure:process.env.NODE_ENV === "production",
        httpOnly:true,
        path:"/",
      })
      const resp = Response.json({
        message:"User already existed and init login",
        
    },{
        status:200
    })
    
    resp.headers.set("Set-Cookie",ck)
    return resp
    }
    try {
        const user = await db.user.create({
          data: {
            id: id,
            email: email,
          },
        });
        const ck = serialize("user_id",user.id,{
          secure:process.env.NODE_ENV === "production",
          httpOnly:true,
          path:"/",
        })
        const resp = Response.json(
          {
              message:"Account is created",
              user: user
          },
          {
              status:201
          }
      )
      resp.headers.set('Set-Cookie',ck);
  
        return resp
      } catch (error) {
        console.log(error)
        return Response.json({ message: 'Failed to save user' },{status:400})
      }
    
  



   
}



```