Back
Leetcode Problems
Array
1D Array2D Array3D ArrayBinary Search
Strings
1D Array2D Array3D ArrayBinary Search
Trees
Introduction to TreesTree Problems
Dynamic programming
1d dp problems2d dp problems
loading image

Please wait a little bit, we are fetching the blogs from the database ....

Back

title: 'NextAuth Setup test-2' author: 'zaheen' publishDate: 'March 4th, 2023' topic : 'strings' subtopic: ['1darray','2darray','cc'] description: 'Get to know about NextAuth and how to setup authentication in Next.js app using NextAuth'

NextAuth Brief Setup Guide

NextAuth.js or Auth.js is an open source community project. It is intended to add authentication to your app in a easy and stream lined way possible. support for various providers like google and github is there.

  • NextAuth.js
  • Auth.js
  • Authentication
  • Next.js

Table of contents Setting up providers in layout.js Configuring various options for authentication in lib/auth.js file Setting up the API route for authentication All set to go

🧑🏽‍💻 Setting up authentication using NextAuth.js is a three step process.

  1. Setting up providers in layout.js
  2. Configuring various options for authentication in lib/auth.js file
  3. Setting up the API route for authentication

Setting up provides in layout.js file

We have to setup a provider for NextAuth in the root layout.js file of Next.js application in order to access the details of authenticated users etc from any where in the app.

to do this we will create a Providers.jsx file in the components folder and we will import this component in the layout.js file and render it

NOTE:

  • This is done because the Providers.jsx file is to be marked as a client component, so instead of making the entire layout a client component we will make only that particular component client side component
  • Also we can keep all other providers (which will also be client side rendered in a single separate file instead of dumping all code in layout.js file )

Copy and paste the below code in components/Providers.jsx file

'use client'

import { SessionProvider } from 'next-auth/react'
import { Toaster } from "@/components/ui/toaster"

const Providers = ({ children }) => {
    return (

        <SessionProvider>
            {children}
            <Toaster />
        </SessionProvider>

    )
}

export default Providers

Copy and past the following code in root layout.js file

import './globals.css'
import { Inter } from 'next/font/google'

import Providers from '@/components/providers'

const inter = Inter({ subsets: ['latin'] })

export default function RootLayout({children})
 {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Providers>
          <div className='max-w-[100rem] mx-auto pt-12'>
            {children}
          </div>
        </Providers >
      </body>
    </html>
  )
}

Configuring various options for authentication

We should configure the authentication based on our needs. it includes specifying which O Auth provider to use etc..

we will create a separate file named auth.js in lib folder as shown below -

import { NextAuthOptions, getServerSession } from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'

export const authOptions = {
  secret:process.env.SECRET,
  providers: [
    GoogleProvider({
      clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
      clientSecret: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_SECRET
    }),
  ],

}

export const getAuthSession = () => getServerSession(authOptions)

This file makes our job a lot easier! . as now we can get the user details for any page in the project.

Make sure to get NEXT_PUBLIC_GOOGLE_CLIENT_ID and NEXT_PUBLIC_GOOGLE_CLIENT_SECRET from google console and add to .env file

Setting up the API route for authentication

Next we have to set up API routes for next auth. the folder structure is app/api/auth/[…nextauth]/route.js the route.js file is the file where we write the logic for the corresponding API. copy past the below code there to finish the setup.

import { authOptions } from "@/utils/auth"
import NextAuth from "next-auth"

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST }

voila there you go

Now you can get the user info sign in and logout user easily. check the below example to get the idea.

"use client"

import { useSession, signIn, signOut } from "next-auth/react"

export default function Component() {
  const { data: session } = useSession()
  if(session) {
    return <>
      Signed in as {session.user.email} <br/>
      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}

: Hey! is your brain fried of this blog? . Well what about a game with me?