NextAuth aims to make authentication simple, yet secure in Next.js apps. it handles automatically practices like passwordless flow, scoping access and more.
With it you can simply get authenticated through your existing logins from different platforms like Google, Atlassian, github, etc.
- Next, recover the clientId highlighted below and then generate client secret.
Then, Fill in the form like this:
NOTE:
- replace "weiterbildung" by the name of your project
- Go to your existing .env file in which you'll save those keys and more sensitive informations, create it if it doesn't exist in your root directory.
Step 2. Create the Authentication API route
- In App Create the directory api/[...nextauth]/route.ts and implement the authentication API route the following way:
// route.ts
import { authOptions } from "@/lib/authOptions";
import NextAuth from "next-auth";
import { AuthOptions } from "next-auth";
const handler = NextAuth(authOptions as AuthOptions);
export { handler as GET, handler as POST };
- Create a provider that will wrap your system, to make all its props available like a context, in your lib directory, create sessionWrapper.tsx where you'll do:
//sessionWrapper.tsx
"use client"
import { SessionProvider } from "next-auth/react"
const SessionWrapper = ({children}: {children: React.ReactNode}) => {
return <SessionProvider>{children}</SessionProvider>
}
export default SessionWrapper;
- implement the SessionWrapper component in layout.tsx after importing it and wrap the layout elements within it, its return should look like this:
//layout.tsx
import SessionWrapper from "../lib/sessionWrapper";
//...some code
return (
<SessionWrapper> //here you are
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<ClientLayout session={session}>{children}</ClientLayout>
</body>
</html>
</SessionWrapper> //here you are
);
Step 3. Set up the connexion between your system and the google and github providers
- In your log-in page or component do the following modification:
//logIn.tsx
"use client"
import { signIn, useSession } from 'next-auth/react';
export default function Login() {
const { data: session } = useSession();
if(session) {
console.log('session', session);
}
return (
<div>
<button
type="button"
onClick={() => signIn('github')}
className="w-full py-2 my-2 border border-red-500"
>Login with Github
</button>
<button
type="button"
onClick={() => {signIn('google')}}
className="w-full py-2 my-2 border border-red-500"
>Login with Google
</button>
</div>
);
}
- In your log-out component do the following modification:
//signOut.tsx
import { signOut } from 'next-auth/react';
export default function Login() {
return (
<div>
<button
type="button"
onClick={() => signOut()}
className="w-full py-2 my-2 border border-red-500"
>Log out
</button>
</div>
);
}
RESULT WITH GOOGLE:
You can choose to get the JWT(Json Web Token) instead of a row object if you want to get your backend involved.
SOCIAL SHARE CARD GENERATOR