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.
- Create a file called [...nextauth].js in pages/api/auth. Add the following code to the file.
- In the pages/_app.js file, import the next-auth SessionProvider. Wrap the app data in the SessionProvider as indicated below.
- 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.
- Create a .env file at the root of your Next.js project
Inside the .env file you will store your google credentials, and other connection data.
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).
Next, update the next.config.js file to allow google user content url.
Get the code for this app here.