By Abdul Rehman
Next-Auth is a great and widely used package in Next.js for Authentication purposes. It provides majority of Auth Providers support built in. A simple Getting Started with Next-Auth could walk you through the quickest implementation of basic authentication system with Next.js project. The problem is, majority of the tutorials over internet are either too old, which means they are using syntax of previous versions, or, they are not using the Credentials Provider at all. What they are providing is the GitHub or Facebook etc Login Providers which could be hassle for beginners.
In this tutorial we are going to make things pretty simple and straight forward for demonstrating the Use of Next-Auth framework in Next js with Credential providers. We are using TypeScript which is super script of JavaScript. So if you know the JavaScript or have some files of JavaScript, don’t worry, your previous JavaScript files are already TypeScript files.
Open Command Prompt and navigate to your project directory, which in my case is “D:/React-Projects”. Now hit the command
npx create-next-app myapp --ts
The –ts will tell that the created project should be supporting the typescript by default.
Now we need to add the support of Next-auth js framework into our project. For that you need to navigate to the myapp directory and type the following npm install command
npm install next-auth
After that, the next-auth library is added to your project.
Now open your project in Visual Studio Code, or one of your favorite IDE, and navigate to api directory and under this directory create a new folder called the auth. Under this directory Create […nextauth].tsx file. This file would be responsible for handling all of the nextauth api routes, like sign in and Sign Out functions. Copy the following code into this file
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
providers: [
CredentialsProvider({
// The name to display on the sign in form (e.g. "Sign in with...")
name: "Credentials",
// The credentials is used to generate a suitable form on the sign in page.
// You can specify whatever fields you are expecting to be submitted.
// e.g. domain, username, password, 2FA token, etc.
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
// Add logic here to look up the user from the credentials supplied
const user = { id: 1, name: "J Smith", email: "jsmith@example.com" }
if(credentials?.username=="test@gmail.com" && credentials?.password=="hello123"){
return user
}else{
return null;
}
}
})
],
callbacks: {
session({ session, token, user }) {
return session // The return type will match the one returned in `useSession()`
},
},
})
Code language: JavaScript (javascript)
After this file added, you are good to use the login system with your Next js project.
You need to modify the _app.tsx file as well so that you would able to use the session variable throughout all pages or the whole project. Here is the code which you need to add so it your app would be aware of where to get the session information
import { SessionProvider } from "next-auth/react"
import type { AppProps } from "next/app"
// Use the <SessionProvider> to improve performance and allow components that call
// `useSession()` anywhere in your application to access the `session` object.
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<SessionProvider
// Provider options are not required but can be useful in situations where
// you have a short session maxAge time. Shown here with default values.
session={pageProps.session}
>
<Component {...pageProps} />
</SessionProvider>
)
}
Code language: JavaScript (javascript)
Now it’s time to use the authentication system. Let’s create a components folder at the root of your project and create following LoginButton components into this folder copy the following code which is taken from the official documentation of the Next-Auth Getting Started guide Page.
import { useSession, signIn, signOut } from "next-auth/react"
export default function LoginButton() {
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>
</>
)
}
Code language: JavaScript (javascript)
save this file as your desired name or in my case login-btn.tsx, this will automatically handle the signIn and signOut states. You can add this into your Layout like following
import React, { ReactNode } from "react";
import Header from "./Header";
import Footer from "./Footer";
import LoginButton from "./login-btn";
import styles from "../styles/Home.module.css"
interface LayoutProps {
children: React.ReactNode
}
export default function Layout({ children }: LayoutProps) {
return (
<>
<Header />
<LoginButton/>
<main className={styles.main}>{children}</main>
<Footer />
</>
)
}
Code language: JavaScript (javascript)
That’s all for now, you are good to use the Next-auth system. If you are interested into the lay outing system we used into this project you may want to check my other tutorial about using Layouts in Next js project. Or if you want to use some back-end database with the Credential provider stay tuned for the upcoming article on this.
19 April 2023
07 April 2023
07 April 2023
FYP Solutions Powered By Impressive Business WordPress Theme