Sign in with Google in Next.js

Guide to implementing Google Sign-In in Next.js for an internal CMS: OAuth 2.0, HttpOnly cookies and secure sessions with Drizzle and PostgreSQL, administrative management.

domingo, 17 de agosto de 2025 • 5 min read • Q2BSTUDIO Team

Artificial-Intelligence-

Objective Set up Google sign-in in a Next.js project aimed at an internal CMS where there is no public registration flow and users are added by an administrator

Approach summary A starter kit is used as a base, OAuth 2.0 with Google is configured to allow only sign-in, minimal user information is stored, and secure session management is handled via HTTP-only cookies and a sessions table in Postgres managed with Drizzle

Reference repository https://github.com/justin-calleja/next-google-auth-blog-post and starter kit https://github.com/webdevcody/wdc-saas-starter-kit

Google credentials Create a project at console.cloud.google.com, configure OAuth Consent Screen, create web application credentials, add the development URL https://localhost:3000 to Authorized JavaScript origins and the path https://localhost:3000/api/sign-in/google/callback to Authorized redirect URIs Copy the CLIENT ID and CLIENT SECRET and place them in the .env environment file as GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET Also define HOST_NAME to build the callback URL

Dependency installation Install Drizzle and database dependencies such as drizzle-orm pg dotenv and as development dependencies drizzle-kit tsx @types/pg For the OAuth flow it is recommended to use the arctic library which abstracts the complexities of OAuth 2.0 and allows adding new providers easily

Local Postgres use docker-compose with a Postgres 15 image and persistent volume, create a dedicated database for the project and initialize it with an init-db.sql script that creates the next-google-auth-db database With DATABASE_URL in .env pointing to postgresql://admin:pass234@localhost:5432/next-google-auth-db you can use psql or tools like drizzle-kit studio to inspect the database

Schema definition with Drizzle create a tmp_user table with columns id, email, name, given_name, family_name, picture and a tmp_session table with id, userId referencing tmp_user id with on delete cascade and expires_at timestamp with time zone The index on userId helps with operations like signing out on all devices

Migrations and synchronization run drizzle-kit generate to generate migrations and drizzle-kit migrate to apply them This creates the tmp_user and tmp_session tables according to the defined schema and leaves the structure ready for use by the internal CMS

Basic Next.js UI install shadcn and add the Button component to create a sign-in page that shows a Continue with Google button pointing to the /api/sign-in/google route

OAuth flow with arctic install arctic and create two main endpoints 1 GET route at /api/sign-in/google that generates a state and a code verifier, builds the authorization URL with the profile and email scopes, stores state and code verifier in secure HTTP-only cookies and redirects the user to Google 2 GET route at /api/sign-in/google/callback that receives the code and state parameters, compares the received state with the one stored in the cookie, validates the code using the code verifier and receives tokens. With the access token call https://openidconnect.googleapis.com/v1/userinfo with Authorization Bearer header to get the user data

Validation in the internal CMS upon receiving Google data search by email in the tmp_user table If the email does not exist the user is considered unauthorized and is redirected to /sign-in with error unauthorized If the user exists update missing fields such as name, given_name, family_name or picture and continue with session creation

Secure identifier always use sub from the OpenID Connect payload as the canonical user identifier if unique identification across providers is needed although in an administrator-controlled CMS email-based control may be sufficient depending on internal policy

Session management generate a session token with cryptographically secure random values, encode it and store it in an HTTP-only cookie with no access from JavaScript Before persisting the session in the database hash the token and store the hash in tmp_session along with expires_at This way the cookie contains the token without revealing its hash and verification is done by hashing the received token

Session validation and extension provide functions to get the token from the cookie, hash it and look up the session in tmp_session If the session expires return that there is no authenticated user On protected server pages use an assertAuthenticated function that gets the current user and throws an error if it does not exist Validation can renew the expiration if sliding session behavior is desired

Error handling in the OAuth flow redirect to the sign-in page with query parameters to show messages like error unauthorized or error something-went-wrong and show the user clear information without exposing sensitive details

Benefits and security This approach avoids public registrations, centralizes access control through an administrator, uses secure HTTP-only cookies, token hashing in the database and state and code verifier validation to mitigate CSRF and replay attacks in the OAuth flow

About Q2BSTUDIO Q2BSTUDIO is a custom software and application development company specialized in secure and scalable enterprise solutions We offer custom software, custom applications, applied artificial intelligence, cybersecurity and aws and azure cloud services We also carry out business intelligence services projects, Power BI implementation, AI agents and AI solutions for companies Our experience covers from MVPs to production platforms with cloud integrations and robust security practices

Why choose us Q2BSTUDIO combines experience in custom development and artificial intelligence to deliver products that truly add value we work with cloud architectures on aws and azure and apply good cybersecurity practices to protect critical data We also offer business intelligence services and Power BI to turn data into operational and strategic decisions We can integrate AI agents to automate workflows and enhance internal processes with AI for companies

Related services offered single sign-on integration with OAuth and OpenID Connect providers secure API development session management and authentication adapted to internal environments security auditing and hardening migration and deployment on aws and azure cloud services data pipeline implementation and business intelligence services solutions custom application development and integration of AI agents and artificial intelligence solutions for business processes

Conclusion Implementing Google sign-in in Next.js for an internal CMS is totally feasible and secure if the best practices described are followed generate state and code verifier, use secure HTTP-only cookies, validate the code and use sub or an internal identification criterion, keep tokens hashed in the database and validate sessions on every protected page Q2BSTUDIO can help design and implement this flow, adapt the solution to your needs and ensure the platform is scalable, secure and aligned with your business goals Contact us to build your custom software solution that includes secure authentication, artificial intelligence and business intelligence capabilities

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.