Skip to content

Instantly share code, notes, and snippets.

@httol
Last active January 21, 2024 06:58
Show Gist options
  • Save httol/7dc3c16eac6c3a490b33c9b9d158e23a to your computer and use it in GitHub Desktop.
Save httol/7dc3c16eac6c3a490b33c9b9d158e23a to your computer and use it in GitHub Desktop.
Custom Email/Password with NextAuth for nextJS project

NextAuth

1.install NextAuth

npm install next-auth

2.under app folder, create route under this folder api/auth/[...nextauth]/route.ts

import NextAuth from 'next-auth/next';
import CredentialsProvider from 'next-auth/providers/credentials'

export const authOptions = {
  providers:[
    CredentialsProvider({
      name:"credentials",
      credentials:{},
      
      async authorize(crendentials){
        const { email, password} = crendentials;
        const user = await getUserInfo(email,password)
        if(user){
          return user;
        }
        return null;
      }
    })
  ],
  session: {
    strategy:"jwt"
  },
  secret: process.env.NEXTAUTH_SECRET,
  pages:{
    signIn:"/"
  }
}

const handler = NextAuth(authOptions);

export {handler as GET, handler as POST};
  1. Create NextAuth session provider for whole app create Providers.ts under app folder
"use client";

import { SessionProvider} from "next-auth/react";

export const AuthProvider = ({children})=>{
  return <SessionProvider>{children}</SessionProvider>
}
  1. Wrap layout SessionProvider
export default function RootLayout({children}){
  return (
    <html lang="en">
      <body>
        <AuthProvider>{children}</AuthProvider>
      </body>
    </html>
  )
}
  1. Implement signIn function
"use client";
...
import { signIn } from "next-auth/react";

const handleLogin = async ()=>{
  const response = await signIn("credentials",{
    email:"YOUR EMAIL",
    password:"YOUR PASSWORD",
    redirect:false
  });
  if(response.success){
    router.replace("/homepage")
  }
}
...
  1. Implement signOut function
"use client";
...
import { signOut } from "next-auth/react";
...
<button onClick={()=>{ signOut(); }}>Log Out</button>
  1. Create middleware.ts under app folder, this means if not logged in, then jump out from homepage
export { default } from "next-auth/middleware";

export const config = { matcher: ["/homepage"]};
  1. To get the logged user information, we can use the useSession hook naturally provided by next-auth library
"use client";
const {data} = useSession();
console.log(data?.user?.email,data?.user?.name);

Note: here we use the default api provided by next-auth. alternatively, for customize your own accessToken, check out Next-Auth-Customize-Token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment