This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Nextjs: Oauth and Credentials authentication with NextAuth


If you happen to’ve been in search of a very good authentication resolution on your Nextjs undertaking you have most likely heard about NextAuth.

NextAuth is a well-liked library with helpful options equivalent to: magic hyperlinks, JWT, Classes with databases, Arbitrary credentials and a (most likely) full record of all of the Oauth 2.0 suppliers! Immediately we’re gonna check out NextAuth.



Let’s Get Began

We’ll construct a easy registration kind. As soon as we efficiently join both with Google, Github, or with our credentials the app will redirect us to a protected web page.

This information is split by two half:

The primary half we’ll look to combine Google and Github registration with our undertaking, This is the reason you may discover the inputs are disabled within the starter undertaking under.

The second half i will speak about registering together with your credentials (i am positive you are already guessed it hehe)

You might also discover this text value having a look at:



Desk Of Contents

  1. Starter Project
  2. Configuration needed for Oauth 2.0
  3. Configuring NextAuth
  4. How does It Work
  5. Signing Up
  6. Protecting the Secret Page
  7. Welcoming the user
  8. Signing Out
  9. Conclusion



Starter Undertaking

Go forward and clone this repo, That is only a easy kind with easy styling
git clone https://github.com/m0nm/next-auth-example // clone the repo
npm set up // set up the deps
npm i next-auth // set up next-auth bundle

sign up form

And right here is the key web page the person will probably be redirected to.
fairly trendy i do know 😂

secret page



Configuration wanted for Oauth 2.0

Earlier than continuing we have to get what is named because the Consumer ID and the Consumer Secret from Google and Github so we are able to use them for our app.



Google

Go to google console and observe me:

create a new project

  • Configure Oauth display screen consent

oauth consent screen

  • Create new Oauth credentials

Word: Since we’re engaged on a neighborhood machine the homepage URL is: “http://localhost:3000“. However when you deploy your app be certain that to vary it to the brand new web site deal with.

Licensed JavaScript origins: http://localhost:3000
Licensed redirect URIs: http://localhost:3000/api/auth/callback/google

create credentials



Github

Go to GitHub Developer website and fill the required fields

Word: Since we’re engaged on a neighborhood machine the homepage URL is: “http://localhost:3000“. However when you deploy your app be certain that to vary it to the brand new web site deal with.
HomePage URL: http://localhost:3000
HomePage Callback URL: http://localhost:3000/api/auth/callback/github

github client id

After you end with the fields hit “Register utility” and Github provides you with the consumer id and the consumer secret.

Retailer them in .env.native file

// .env.native
GOOGLE_ID="YOUR GOOGLE CLIENT ID"
GOOGLE_SECRET="YOUR GOOGLE CLIENT SECRET"

GITHUB_ID="YOUR GITHUB CLIENT ID"
GITHUB_SECRET="YOUR GITHUB CLIENT SECRET"
Enter fullscreen mode

Exit fullscreen mode

After we obtained what we want now we are able to proceed.



Configuring NextAuth

To Add NextAuth to our app create a file known as [...nextauth].js in pages/api/auth. It is a catch-all dynamic route handler, which means that each one requests (signIn, signOut) will probably be dealt with by NextAuth

import NextAuth from "next-auth"
import GoogleProvider from "next-auth/suppliers/google"
import GithubProvider from "next-auth/suppliers/github"

export default NextAuth({
  suppliers: [
    // Configure Google
      GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      }),

   // Configure Github    
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    })
  ],
})
Enter fullscreen mode

Exit fullscreen mode

We additionally must wrap our app inside SessionProvider

import "../kinds/globals.scss";
import { SessionProvider } from "next-auth/react";

perform MyApp({ Element, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <Element {...pageProps} />
    </SessionProvider>
  );
}

export default MyApp;

Enter fullscreen mode

Exit fullscreen mode

And that is it! NextAuth is prepared for use.



How Does It Work

the NextAuth bundle present a consumer aspect hook useSession and a server aspect methodology getSession. These two return a session object which we are able to use to guard a web page or to conditionally render a element.

const {knowledge: session} = useSession()
Enter fullscreen mode

Exit fullscreen mode

The session object will typically seems like this

session: {
    person: {
        title: "person title", 
        e mail: "person e mail",
        picture: "person picture"
    }
}
Enter fullscreen mode

Exit fullscreen mode

The bundle additionally present us with signIn and signOut strategies. We are able to know their use intuitively by their title.



Word!

The signIn() methodology acceptes a string that symbolize a supplier (ex: “google” or “github”), If you happen to do not specify an argument, the tactic will redirect the person to the built-in register web page. Which we do not need in our case

// This may redirect the person to built-in signal web page
<button onClick={() => signIn()}>Signal In</button>

// This may skip the built-in web page and redirect the person on to the google Oauth sign-in movement
<button onClick={() => signIn("google")}>Signal In</button>
Enter fullscreen mode

Exit fullscreen mode



Signing Up

Now all we is to fireplace signIn when a person click on on Google or Github register button.

// ./pages/index.js

import React from "react"
import {signIn} from "next-auth/react"

perform Dwelling() {

    const handleSignIn = (supplier) => {
       // the redirect url have to be an absolute url!     
        const redirect = window.location.href + "/secret"

        signIn(supplier, {callbackUrl: redirect})
    }

    return (
    {/* oauth */}

      {/* google */}
      <button 
          onClick={() => handleSignIn("google")}
          className={kinds.oauth}>
        <Picture src={googleSvg} width="18" top="18" alt="" />
        <span>Enroll with Google</span>
      </button>

      {/* github */}
      <button 
          onClick={() => handleSignIn("github")}
          className={kinds.oauth}>
        <Picture src={githubSvg} width="18" top="18" alt="" />
        <span>Enroll with Github</span>
      </button>
    )
}
Enter fullscreen mode

Exit fullscreen mode

After the person efficiently register he will probably be redirected to the protected web page as a result of we specified callbackUrl choice for signIn methodology

// the redirect url have to be an absolute url!
const redirect = window.location.href + "/secret"

signIn(supplier, {callbackUrl: redirect})
Enter fullscreen mode

Exit fullscreen mode



Defending the Secret Web page

To guard this web page we have to verify if there’s a session, If none the person will probably be routinely redirected to the beginning web page.

We’ll use the getSession methodology on the server aspect to verify for session and to deal with redirection.

// ./pages/secret.jsx
import {getSession} from "next-auth/react"

perform Secret() {
    ...
}


export const getServerSideProps = async (context) => {
  // get the session
  const session = await getSession(context);

  // redirect the person if there is no such thing as a session   
    if (!session) {
    return {
      redirect: {
        vacation spot: "/",
        everlasting: false,
      },
    };
  }

  return { props: {} };
};  
Enter fullscreen mode

Exit fullscreen mode

As you may see we’re utilizing the redirect key if no session was supplied by getSession



Welcoming the person

We are able to use the session object we get from getSession to render the person title within the secret web page

import React from "react"
import {getSession} from "next-auth/react"

perform Secret() {

    return (
        <h1>Hiya mr {session.person.title}</h1>
        <p>You might be licensed to see this web page</p>  
    )
}

export const getServerSideProps = async (context) => {
  // get the session
  const session = await getSession(context);

  // redirect the person if there is no such thing as a session   
    if (!session) {
    return {
      redirect: {
        vacation spot: "/",
        everlasting: false,
      },
    };
  }

 // passing the session object to the web page  
  return { props: {session} };
};  

Enter fullscreen mode

Exit fullscreen mode



Signing Out

Identical to with signing in, We now have to fireplace signOut when the person click on on signal out button

import React from "react"
import {signOut} from "next-auth/react"

perform Secret() {
    const handleSignOut = () => {
        signOut()
    }
    return (
        ...
     <button onClick={handleSignOut}>Signal Out</button>
    )
}
Enter fullscreen mode

Exit fullscreen mode

And now our app is working, Here is the final code



Conclusion

We have reached the tip of this submit, If it was useful to you i’d recognize it if you happen to depart a ❤️. See you quickly on the subsequent half!

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?