How to get started with NextAuth ?

How to get started with NextAuth ?

Create your own credentials provider in NextAuth

An important segment of a web application is authentication. Authentication with NextJS could be done by storing the JWT token in the local storage but it is not preferred as it could lead to some security issues like

1 . Cross-site Scripting (XSS) Attacks

2. Persistent Storage

3. Limited Security Features

localStorage.setItem(token, "jwt123");

Instead of storing the JWT token in localStorage it could be stored in the cookies as it provides the in-built CSRF Protection and cookies are mostly controlled by server including flags, expiration times etc.

cookies().set('name', 'lee')

One of the primary challenges with cookies is the need to access and verify them with every incoming request on the server. This constant validation can burden server resources and complicate the authentication logic, especially in large-scale applications with numerous concurrent users.

To streamline authentication processes and overcome the complexities associated with traditional authentication methods, developers often turn to authentication libraries. One such powerful tool that simplifies authentication in Next.js applications is NextAuth JS.

To get started feel free to install the library by typing below code in terminal

npm install next-auth

Next step is to create the below mentioned file structure.

Now create your own authentication for email/password by pasting the below code in route.ts

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { AuthOptions } from "next-auth";

const authOptions: AuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        const email = credentials?.email;
        const password = credentials?.password;

        try {
          // database call
          return {
                id : user.id
            }
        } catch (e) {
          return null;
        }
      },
    }),
  ],
};

const handler = NextAuth(authOptions);

export const GET = handler;
export const POST = handler;

The above code would generate a login page at the api/auth/signin endpoint where user can login by entering their email and password.

When a user successfully authenticates through NextAuth.js, it generates a JWT containing authentication-related information. This JWT serves as a session token and is typically stored securely on the client side, often in a cookie.

Now Programmers need not worry about authentication. NextAuth library will take care of authentication like retrieving the cookie verifying its authenticity and returning the response.

Next.js 13 and Next Auth by Praveen Jayakody | Ascentic Technology