Authenticate nextjs application with hanko frontend auth.

ismailmirza

Mohammad Ismail Mirza

Posted on January 7, 2024

Authenticate nextjs application with hanko frontend auth.

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"
Enter fullscreen mode Exit fullscreen mode

Now install hanko frontend-elements

yarn add @teamhanko/hanko-elements

Enter fullscreen mode Exit fullscreen mode

now run development server

yarn dev
Enter fullscreen mode Exit fullscreen mode

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

Image description
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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Finally, set up Prisma with the init command of the Prisma CLI:

yarn prisma init 
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

Now connect with postgresql database

datasource db {
  provider     = "postgresql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}
Enter fullscreen mode Exit fullscreen mode

Create model named user to store the login user in backend



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

}
Enter fullscreen mode Exit fullscreen mode

Now run this command to migrate database.

yarn prisma migrate dev --name init

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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})
      }






}



Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ismailmirza
Mohammad Ismail Mirza

Posted on January 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related