Skip to content
Ref » Home » Blog » How To » Designing

Next.js Client-Side Authentication Steps Using NextAuth.js

Here is a guide about how to implement the Next.js Client-Side Authentication using NextAuth.js easily. No matter what kind of application you’re creating, you’ll want to ensure that you’re adding client-side authentication to it. Your client should be asked for a username and password at minimum, so the application knows they are who they say they are.

However, there are ways that you can get authentication that doesn’t require a password. That includes using third-party accounts, such as someone’s Facebook account, Google login, or GitHub login. When these are used, various details can be brought over, such as the user’s display name, avatar, and more.

Next.js Client-Side Authentication is a critical aspect of web apps with key perspectives being: client-side, server-side, and API route authentication. And, as such, you would want to set up client-side authentication, Sign Out, and Sign In functionality, and prevent unauthorized users keep from accessing protected routes on the client side with the NextAuth.js framework.

If you want to do this in your application, then you can implement it using NextAuth.js. That said, let’s now learn in a few simple steps how to set up authentication on the client side in Next.js for beginners, and then, offer this option to your users.

Next.js Client-Side Authentication Steps Using NextAuth.js

Firstly, you need to understand what these two tools (Next.js and NextAuth.js) are before we can get started. Next.js is a framework that’s used with React, built on top of it to make building apps using the React system very easy to do. It offers a lot of power with no config work needed on your end. As such, NextAuth.js is an authentication solution for Next.js.

So that you can allow for authentication in the application platform that you’re building. “This solution is designed to sync with any OAuth device, making it very easy to use,” says Melissa Chowdry, a tech blogger at Dissertation Help and UKWritings per see. “As such, you can create sign-in options that don’t require passwords.”

Typically, NextAuth.js can be used with popular databases such as MySQL Database, MongoDB, PostgreSQL, and MariaDB. Basically, authentication in Next.js Apps falls into two broad perspectives.

Consider the following:
  1. Page authentication
    • Client-side
    • Server-side
  2. API route authentication

Before you implement any authentication, you need to have a clear understanding of what data-fetching strategy you are going to use in your application. On that note, you can read about data-fetching strategies in the following posts.

  1. Server-Side Rendering ( SSR )
  2. SSG, Pre-Rendering, And GetStaticProps
  3. Client-Side Data Fetching

Client-side authentication is for those websites that use SSG( static-site generation ). It can combine client-side data fetching libraries such as SWR( recommended by the Next.js team ) once the user is authenticated. Specifically, authentication on the client side has a variety of patterns that drives its overall performance and actual workability.

Consider the following patterns:
  1. First, the browser sends a request to the static page on Next.js App
  2. Secondly, the Next.js app renders an initial static loader/loading-skeleton
  3. Thereafter, the browser sends the authentication request to the backend API route
  4. Lastly, based on the response, the user will be redirected to the requested page(ex: the dashboard ) or the Sign In page

One of the benefits of NextAuth.js is that you don’t need to be an expert in identity protocol. That makes it easier than using a system like Oauth to build an authentication system in Next.js apps. Another top benefit is that you won’t need to store any sensitive data, too. That means you won’t need to worry about being liable for the loss of that data if there’s ever a breach.

NextAuth.js is so simple, it only needs 20 lines of code to be implemented and used in your app. When you use it, it uses the client-side API to gain information from providers, and display it to users upon successful login. When you use it, you’ll see there’s no sensitive data in the code that’s returned. All the data that’s presented in the session payload is presentational.

Or rather, it’s designed to be shown to the user. It’s also important to note that NextAuth.js uses React Hook, which is what’s used to check the user login status. It also provides a REST API that is used by the React app.

The Steps For Setting Up A Next.js Starter Application

Now you know the basics, you can set up your own Next.ja start the app, so you can see how this all works. You can begin by using the command npx create-next-app gfgOnce you’ve done this, you’re ready to install NextAuth.js using the command npm I next-auth.

Once this is done, you’ll need to go to the Google developer console and get your Oauth API ID and key. Now, this is done, create a new folder inside the page/API directory and name it ‘auth’. In that folder, create a new file with the name ‘[nextauth].js.’ You’ll now be ready to import NextAuth and GoogleProvider from next-auth.

In simple terms, NextAuth.js is an open-source authentication library that supports authentication requirements in Next.js Apps. We are going to create a simple app to demonstrate how to use this library to set up client-side authentication.

Setting up the development environment

  1. First, run npx create-next-app next-auth-app on the terminal.
  2. then install next-auth: npm install next-auth

It’s, important to realize, that NextAuth is bundled with a variety of built-in Authentication providers that you can utilize for free. Whereby, you can consider using Google authentication in your app as the starting point.

After all, “You can use other authentication providers if you wish to,” says technical writer Dan Matthews, from Research Paper Help and OXEssays to be specific. “In this example though, Google will be the only provider.” Add the provider on every page, using the correct code to do so in the _app.js file. In your project folder structure, go to the pages/ index.js.

Setting up the application

In terms of setting up the app context, you are going to need to build a simple UI for your app first. Just make sure that you replace the default code generated with the code below:

import Styles from '../styles/Home.module.css'
import Link from 'next/link';
 
 
 
function Home() {
   
  return (
    <div><p>Welcome, to Next.js authentication</p>
        <ul className={ Styles.nav_container }>
          <li className={ Styles.list }>
            <Link href="/">
              <a className={ Styles.nav_button }>Home</a>
            </Link>
          </li>
         
          <li className={ Styles.list }>
            <Link href="/dashboard">
              <a className={ Styles.nav_button }>Dashboard</a>
            </Link>
          </li>          
       
          <li className={ Styles.list }>
              <Link href="#">
                <a className={ Styles.nav_button }>Sign in</a>
              </Link>
          </li>      
       
          <li className={ Styles.list }>
            <Link href="#">
              <a className={ Styles.nav_button }>Sign Out</a>
            </Link>
          </li>
       
        </ul>
    </div>
  )
}
 
export default Home

In styles/Home.module.css, replace the CSS styles with the following:

.nav_container{
  display: flex;
}
 
.bgcolor{
  background-color: aliceblue;
}
 
.list{
  list-style: none;
}
 
.nav_button{
  padding: 5px 10px;
  margin: 5px;
  border-radius: 2px;
  background-color: lightgray;
}
 
.loading {
  opacity: 0;
  transition: all 0.2s ease-in;
}
 
.loaded {
  opacity: 1;
  transition: all 0.2s ease-in;
}

Running the app in dev mode

Now, run the application in the development mode using the following command lines:

npm run dev

By doing so, you should see a simple app with four links. Technically, this is sufficient to understand client-side authentication.

A Simple UI To Test The Next.js Client-Side Authentication Process

As you can see, you’re able to add log-in/log-out buttons on your home page. You’ll use the useSession () hook to check whether a user is logged in or not. This will check if a session exists or not. If it does, that means the user is already logged in and you’re showing them the ‘log out’ button. If they aren’t, then you’ll be showing them the ‘log-in’ button.

Of course, it’s really as simple as that! You can use NextAuth.js to offer log-in options through third parties, enabling passwordless entry to the app, and ensuring that you don’t need to store any personal data for your clients.

Adding the main authentication provider

NextAuth.js provides four ways to authenticate users, you may consider using;

  • a built-in OAuth Provider (e.g Github, Twitter, Google, etc…)
  • a custom OAuth Provider
  • Email
  • Credentials

In your sample app above, you may try to use a built-in OAuth Provider such as the Google App Authentication Tools to authenticate the potential users of your application. First of all, create a Google account if you do not have one.

Secondly, sign in to your Google account and open the Google API Console to set up your own credentials. If this is your first time working with Google console to add OAuth client ID credentials, you have to add a new project in the console.

Protecting dashboard route on the client side

Be that as it may, if you did everything correctly, you should be able to access all the routes by clicking the links on the home page. However, if someone enters http://localhost:3000/dashboard in the browser directly without signing in, he can still be able to access the dashboard.

Therefore, you’ll need to protect this page from unauthenticated access. To do this on the client side, you can use the useSession hook. Whereas, you can use the value of the status to check if a user is authenticated or not.


About The Author:

Jenny Han is a writer for Write My Term Paper and Buy Assignment services. Besides bringing you this great article herein, she covers coding and digital marketing, and she’s also a contributor to the Essay Writer blog.

More Related Resource Articles


Explore Blog Tags:


Get Free Updates!