Best Website-BuildersBest Website-Builders
    What's Hot

    Here Are the Skills You Need to Succeed in Tech in 2023

    March 19, 2023

    Seven missing after blaze destroyed Old Montreal building, fire officials say

    March 19, 2023

    Formula 1: Sergio Perez wins in Saudi Arabia as Fernando Alonso loses podium

    March 19, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      How to integrate Google authentication into your Next.js app using NextAuth

      March 19, 2023

      10 text styling properties in CSS

      March 19, 2023

      Learn more about how web browsers work (with illustrations) ⚙️🚀 | Tapajyoti Bose | | March 2023

      March 19, 2023

      Learn more about how web browsers work (with illustrations) ⚙️🚀 | Tapajyoti Bose | | March 2023

      March 19, 2023

      New statement on stolen 20,000 fentanyl vials

      March 19, 2023
    • Joomla

      How Superior Web Hosting Support Can Drive Business Success

      March 17, 2023

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023

      Bluehost Review: Best Solution for Your Web Hosting Needs? – WISH-TV | Indianapolis News | Indiana Weather

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023
    • PHP

      10 reviewer-approved tools that actually remove pet hair from your stuff

      March 19, 2023

      Wyoming is the first state to ban abortion pills

      March 18, 2023

      Expert-Recommended Home Office Hacks For Those Fighting The Winter Blues

      March 18, 2023

      paris hilton book review

      March 18, 2023

      Spring depression is real. Here’s why you might feel sick right now.

      March 18, 2023
    • UX

      E-Commerce, Driven by User Experience, Rapidly Transforms $308 Billion GCC Retail Sector – News

      March 19, 2023

      Job posting law creates rift between employees and employers over fair wages

      March 19, 2023

      Chompi Club announces new tape music instrument News ⟋ RA

      March 19, 2023

      Lexus creates a special edition of the UX 250h F Sport Design

      March 18, 2023

      3 Lessons Web3 Founders Can Learn From ChatGPT’s Success

      March 18, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Apple’s foldable iPhone may automatically close to protect itself from finger malfunction

      March 18, 2023

      If the trend continues, hard drives could finally hit the market by Christmas

      March 18, 2023

      The Google Pixel Fold could be the phone that makes foldables affordable.tech radar

      March 18, 2023

      Google Photos could soon bring its AI editing capabilities to videos

      March 17, 2023

      Windows 11 update coming soon to make your PC more stable

      March 17, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to integrate Google authentication into your Next.js app using NextAuth
    CSS

    How to integrate Google authentication into your Next.js app using NextAuth

    websitebuildersnowBy websitebuildersnowMarch 19, 2023No Comments6 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Integrating a secure authentication system is an important development step that not only provides users with a safe environment, but also instills confidence in the product. This system ensures that your data is protected and that only authorized individuals can access your application.


    Building secure authentication from scratch can be a time-consuming process and requires a thorough understanding of authentication protocols and processes, especially when dealing with different authentication providers.

    NextAuth lets you focus on building core functionality. Learn how to integrate Google Social Login into your application using NextAuth.


    How NextAuth Works

    NextAuth.js is an open-source authentication library that simplifies the process of adding authentication and authorization functionality to your Next.js applications, as well as customizing authentication workflows. It offers various features such as email, passwordless authentication, support for different authentication providers such as Google, GitHub, etc.

    Login page appears on samsung device

    At a high level, NextAuth acts as middleware, facilitating the authentication process between your application and your provider. Internally, when a user tries to log in, they are redirected to Google’s sign-in page. After successful authentication, Google returns a payload containing the user’s data such as name and email address. This data is used to authorize access to the application and its resources.

    Using payload data, NextAuth creates a session for each authenticated user and stores the session token in a secure HTTP-only cookie. A session token is used to verify a user’s identity and maintain authentication status. This process also applies to other providers with slightly different implementations.

    Register your Next.js application with the Google Developer Console

    NextAuth provides support for Google Authentication Service. However, if you want your application to interact with Google APIs and allow the user to authenticate with her Google credentials, register your app in the Google Developer Console and client ID and client secret.

    To do this, go to the Google Developer Console. Then sign in with your Google account to access the console. Once logged in, create a new project.

    Create a project in Google Developer Console

    On the project overview page, APIs and services Select a tab from the list of services in the left menu pane and finally Qualification option.

    Google Developer Console Settings

    please click Create Credentials Click the button to generate a Client ID and Client Secret. Then, specify the type of application from the options given and provide the name of the application.

    [資格情報の作成]Click the button to set your Google Client ID and Secret

    Then specify the app’s home root URL and finally the application’s authorized redirect URIs.In this case it is http://localhost:3000/api/auth/callback/google As specified in the Google provider settings for NextAuth.

    OAuth client settings

    After completing the registration, Google will give you a Client ID and Client Secret to use in your app.

    NextJS application setup

    First, create a Next.js project locally.

     npx create-next-app next-auth-app 

    Once setup is complete, navigate to the newly created project directory and run this command to start the development server.

     npm run dev 

    Open a browser and go to http://localhost:3000. This should give the expected result.

    Nextjs dev server startup screen

    .env file settings

    In the root folder of your project, create a new file and give it a name. .env Keep your client ID, secret, and base URL.

     NEXT_PUBLIC_GOOGLE_CLIENT_ID= 'client ID'
    NEXT_PUBLIC_GOOGLE_CLIENT_SECRET= 'secret'
    NEXT_PUBLIC_NEXTAUTH_URL= 'http://localhost:3000'

    NextAUTH URL is used to specify the base URL of the application. This is used to redirect the user after authentication is complete.

    Integrate NextAuth in your Next.js application

    First, install the NextAuth library into your project.

     npm install next-auth 

    next, /page directory, create a new folder and name it APIs. directory to APIs Create another folder called certification In the auth folder, add a new file and name it […nextauth].js Add the following lines of code.

     import NextAuth from "next-auth/next";
    import GoogleProvider from "next-auth/providers/google";
    export default NextAuth({
        providers:[
            GoogleProvider({
                clientId:process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
                clientSecret: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_SECRET,
            }),
        ]

    });

    This code configures Google as an authentication provider. The NextAuth function defines a Google provider configuration object that receives her two properties client id and client secret to initialize the provider.

    next, pages/_app.js Open the file and make the following changes to your code.

     import '../styles/globals.css'
    import { SessionProvider } from "next-auth/react"
    function MyApp({ Component, pageProps: { session, ...pageProps } }) {
     return (
       <SessionProvider session={session}>
         <Component {...pageProps} />
       </SessionProvider>
     )
    }
    export default MyApp

    of NextAuth session provider The component provides authentication state management functionality for Next.js apps.it takes session A prop containing authentication session data returned from Google’s APIs, including user details such as ID, email, and access token.

    By wrapping My app When used with the SessionProvider component, an authenticated session object containing user details is made available throughout the application, allowing the application to persist and render pages based on authentication state.

    Configure the index.js file

    open page/index.js Open the file, remove the boilerplate code, and add the code below to create a login button that routes the user to the login page.

     import Head from 'next/head'
    import styles from '../styles/Home.module.css'
    import { useRouter } from 'next/router';

    export default function Home() {
      const router = useRouter();
      
      return (
        <div className={styles.container}>
          <Head>
            <title>Create Next App</title>
            <meta name="description" content="Generated by create next app" />
            <link rel="icon" href="/favicon.ico" />
          </Head>

          <main className={styles.main}>
            <h1 className={styles.title}>
              Welcome to <a href="https://nextjs.org">Next.js!</a>
            </h1>

            <p className={styles.description}>
              Get started by signing in{' '}
              <code className={styles.code}>with your Google Account</code>
              <button className={styles.loginButton}
              onClick={() => router.push('/Login')}> Login</button>
            </p>
          </main>

        </div>
      )
    }

    This code uses Next.js Router used Use hooks to handle routing within your application by defining a router object.When the login button is clicked, the handler function is router.push A method that redirects the user to the login page.

    Create a login authentication page

    in the page directory, create new file login.jsthen add the following lines of code:

     import { useSession, signIn, signOut } from "next-auth/react"
    import { useRouter } from 'next/router';
    import styles from '../styles/Login.module.css'

    export default function Login() {
      const { data: session } = useSession()
      const router = useRouter();
      if (session) {
        return (
          <div className={styles.container}>
            <h1 className="title">Create Next App</h1>
            <div className={styles.content}>
                 <h2> Signed in as {session.user.email} <br /></h2>
                  <div classname={styles.btns}>
                  <button className={styles.button} onClick={() => router.push('/Profile')}>
                     User Profile
                 </button>
                  <button className={styles.button} onClick={() => {
                      signOut()
                  }}>
                     Sign out
                 </button>
                  </div>
            </div>
          </div>

        )
      }
      return (
        <div className={styles.container}>
           <h1 className="title">Create Next App</h1>
          <div className={styles.content}>
              <h2> You are not signed in!!</h2>
          <button className={styles.button}
          onClick={() => signIn()}>Sign in</button>
          </div>
        </div>
      )
    }

    useSession, loginand sign out is a hook provided by next certification. useSession Hooks are used to access the current user session object once the user is signed in and successfully authenticated by Google.

    This allows Next.js to persist authentication state and render user details on the client side of the app (email in this case).

    Additionally, the session object allows you to easily build custom user profiles for your application and store data in databases such as PostgreSQL. You can use Prisma to connect your PostgreSQL database to your Next.js application.

    The signOut hook allows users to sign out of your application. This hook removes the session object created during the sign-in process and the user is signed out.

    Spin up your development server, update your changes, and navigate to your Next.js application running in your browser to test the authentication functionality.

     npm run dev 

    Additionally, you can use Tailwind CSS in your Next.js app to style the authentication model.

    Authentication using NextAuth

    NextAuth supports multiple authentication services that can be easily integrated into your Next.js application to handle client-side authentication.

    Additionally, NextAuth provides support for various database integrations, so you can integrate databases that store user data and access tokens to implement server-side authentication for subsequent authentication requests.



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleCar gets wedged outside historic Bath hotel
    Next Article Norfolk council sorry for wrongly telling man he is dead
    websitebuildersnow
    • Website

    Related Posts

    10 text styling properties in CSS

    March 19, 2023

    Learn more about how web browsers work (with illustrations) ⚙️🚀 | Tapajyoti Bose | | March 2023

    March 19, 2023

    Learn more about how web browsers work (with illustrations) ⚙️🚀 | Tapajyoti Bose | | March 2023

    March 19, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    Here Are the Skills You Need to Succeed in Tech in 2023

    March 19, 2023

    Seven missing after blaze destroyed Old Montreal building, fire officials say

    March 19, 2023

    Formula 1: Sergio Perez wins in Saudi Arabia as Fernando Alonso loses podium

    March 19, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.