Sign In with Google at Next.js and Next-Session

2022/11/22 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Requirements
  3. Add Google Sign-In callback
  4. Use with next-session
  5. Conclusion


This tutorial shows how to integrate sign in with Google account, and how to handle callback response from Google Sign-In.


  • GCP
    • Has knowledge of using Google Cloud.
    • Already setup google sign-in setting OAuth Client ID and Secret at Google Cloud, or reference here for how to setup Google Sign.

Add Google Sign-In callback

Once setup the Google Sign-In, OAuth Client, and redirect URLs, then first thing we can do is add call back function at the application to handle the response sending by the Google Sign In.

If define as below as http://localhost:3000/api/auth/callback/google, then once user successfully sign-in with google will redirect to that URL with JWT token, so will need logic to process the information, for instance, save the name, email to the database, or save the email to the session. So this article will demonstrate how to use next-session to save to the session, cookie and how to clear session build custom logic with logout function.

OAuth Create Screen

Below is sample code, so once google callback come to this function, you can start parse the credential as jwt token, then read the value from, for instance below you should be able to get name and email who successfully sign-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 =;

const email =;


Use with next-session

Once build callback function, you need to store those information at the web application. One of the way to do is using the next-session.

export const getSession = nextSession({
  cookie: {
    sameSite: 'lax',
    maxAge: 60 * 60 * 24 * 365,


This blog demo example code how to google sign-in callback works and how you can using next-session to store user specific information across your application.