2024-09-09 web, development, javascript
Next Auth with Google
By O. Wolfson
NextAuth.js for Next.js provides built-in authentication via google. Follow the steps below to enable user authentication from your google account.
You can start with a clean Next.js installation to follow along.
- Install NextAuth. From the root of your project folder, enter the following command in a terminal.
bashyarn add next-auth
- Create a file called [...nextauth].js in pages/api/auth. Add the following code to the file.
javascriptimport NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
secret: process.env.JWT_SECRET,
});
- In the pages/_app.js file, import the next-auth SessionProvider. Wrap the app data in the SessionProvider as indicated below.
javascriptimport { SessionProvider } from "next-auth/react";
function MyApp({ Component, pageProps, session }) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
}
export default MyApp;
- In your pages/index.js file import useSession, signIn and signOut methods from next-auth.
Create a constant to hold the current auth session. Create two buttons. The first button's onClick property can run the signIn method and the second button can run signOut. Next add a div to display the logged-in user's name. This div should display if there is a current login session.
javascriptimport { useSession, signIn, signOut } from "next-auth/react";
export default function Home() {
const { data: session } = useSession();
return (
<div>
<button onClick={() => signIn()}>Log In</button>
<button onClick={() => signOut()}>Log Out</button>
<div>{session && `Welcome ${session.user.name}`}</div>
</div>
);
}
- Create a .env file at the root of your Next.js project
bashtouch .env
Inside the .env file you will store your google credentials, and other connection data.
javascriptGOOGLE_CLIENT_ID=<your google client id>
GOOGLE_CLIENT_SECRET=<your google client secret>
NEXTAUTH_URL=<your NextAuth url>
JWT_SECRET=<your jwt secret>
Paste in the proper data for each of these variables.
Log into your Google account and go to Google Cloud Console to generate your credentials, the GOOGLE_CLIENT_ID and the GOOGLE_CLIENT_SECRET. Click on the + CREATE CREDENTIALS button. Select the OAuth Client ID option. Select Web Application as your "Application type". Enter a name for the credentials. Add a URI in the Authorized JavaScript Origins. For a Next.js project that will typically be http://localhost:3000
. Note that for production deployment of your app you will need to add a procution url as well. Also add an Authorized redirect url as follows http://localhost:3000/api/auth/callback/google
Press Create. Copy the credentials generated.
To generate your JWT_SECRET go to this url https://generate-secret.vercel.app/32 and copy the generated numeric string.
- Bonus display an image of the user from google account.
First add the following code where your ui is being rendered (index.js in this example).
javascript{
session && <Image alt="user image" imgSrc={session.user.image} />;
}
Next, update the next.config.js file to allow google user content url.
javascriptmodule.exports = {
images: {
domains: ["lh3.googleusercontent.com"],
},
};
Get the code for this app here.