Sign In with Google at Next.js and Next-Session
Table of Contents
Introduction
This tutorial shows how to integrate Sign In with Google and how to handle the callback response from Google Sign-In.
Requirements
- GCP
- Has knowledge of using Google Cloud.
- Already set up Google Sign-In with OAuth Client ID and Secret at Google Cloud, or reference here for how to set up Google Sign-In.
Add Google Sign-In Callback
Once you've set up Google Sign-In, the OAuth Client, and redirect URLs, the first thing you can do is add a callback function in the application to handle the response sent by Google Sign-In.
If you define the redirect URL as http://localhost:3000/api/auth/callback/google, then once the user successfully signs in with Google, they will be redirected to that URL with a JWT token. You'll need logic to process the information — for instance, saving the name and email to the database, or saving the email to the session. This article will demonstrate how to use next-session to save to the session and cookie, and how to clear the session with a custom logout function.

Below is sample code. Once the Google callback reaches this function, you can parse the credential as a JWT token, then read the values from it. For instance, you should be able to get the name and email of the user who successfully signed in with Google.
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
const credential = req.body.credential;
const jwtToken = JSON.parse(Buffer.from(credential.split('.')[1], 'base64').toString())
const name = jwtToken.name;
const email = jwtToken.email;
}
Use with next-session
Once you build the callback function, you need to store the information in the web application. One way to do this is by using next-session.
export const getSession = nextSession({
cookie: {
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 365,
}
});
Conclusion
This blog demonstrated example code showing how the Google Sign-In callback works and how you can use next-session to store user-specific information across your application.