How to use NextAuth in NextJS 13?
Hey folks,
On this tutorial, I will teach you how to implement NextAuth in NextJS13.
Here are the steps we need to do:
- Install NextAuth
- Create env file
- Create a google api key clientId and clientSecret
Install NextAuth
npm i next-auth
or yarn add next-auth
Create a google api keys
Create a google keys by going to google developers
or by following this official tutorial
Create env file
Create env file in the same level as your app directory and add the keys to it.
Code Implementation
Once done, we can start the fun part!
Create api\auth[...nextauth] folder inside the app directory. After that create a file called route.ts
. Your folder should look like this
and paste this code
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
/*
Note: No secret provided since it's provided in .env.local
read more: https://next-auth.js.org/configuration/options#secret
*/
const handler = NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID!,
clientSecret: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_SECRET!,
}),
],
session: {
maxAge: 60 * 60, // 1 hour
},
});
export { handler as GET, handler as POST };
Now we're done implementing our next auth route. The next step will be implementing our SessionProvider.
SessionProvider
Now go to your layout.tsx
file and add SessionProvider from NextAuth.
Your code should look like this
'use client'
import { SessionProvider } from "next-auth/react";
import { Poppins } from "next/font/google";
import "normalize.css";
const inter = Poppins({
weight: ["300", "500", "600", "700"],
subsets: ["latin"],
});
export const metadata = {
title: "Sneak",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<SessionProvider>
<main>{children}</main>
</SessionProvider>
</body>
</html>
);
}
Page
Now we will implement the signIn and signOut functions. Go to your page.tsx and copy this code. We will also check if the user is authenticated or not
"use client";
import { signIn, signOut, useSession } from "next-auth/react";
const Home = () => {
const { data: session, status } = useSession();
const handleSignin = () => {
signIn("google");
};
const handleSignout = () => {
signOut();
};
// this if condition will check if the user is authenticated or not
if (status === "authenticated") {
return (
<div>
<h1>{session.user?.email}</h1>
<button onClick={handleSignout}>Logout</button>
</div>
);
}
return (
<div>
<button onClick={handleSignin}>Login Button</button>
</div>
);
};
export default Home;
Aaaaaaaand we're done!
Bonus! NextAuth with Middleware
What is middleware? Middleware will run before any page is rendered on the browser. It means, we can protect our pages from unauthorize users.
Create a middleware.ts
file with the same level as your app.
It should look like this
Now, inside the middleware file, paste this code
export { default } from "next-auth/middleware";
// this code will protect any attempts from unauthorize users that will try to access protected route.
export const config = { matcher: ["/protected/:path*"] };
Any unauthorize users will be force to signIn using their Google Accounts.
Thanks for reading!
Top comments (0)