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};
- 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>
}
- Wrap layout SessionProvider
export default function RootLayout({children}){
return (
<html lang="en">
<body>
<AuthProvider>{children}</AuthProvider>
</body>
</html>
)
}
- 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")
}
}
...
- Implement signOut function
"use client";
...
import { signOut } from "next-auth/react";
...
<button onClick={()=>{ signOut(); }}>Log Out</button>
- 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"]};
- 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