Cookies, Sessions and Sign In with Google (OAuth)

Node.js and Express: Build a Back End API from Scratch · Authentication and Security · 7 min read · Updated

Cookie plus server memory

  1. A successful login, by password or by a verified Google token, starts a session.
  2. The server stores the data and creates a random session id.
  3. Only the id travels in a signed, httpOnly, sameSite cookie.
  4. The browser sends it back, and the server looks up the record. Deleting the record is logout.

JWTs are not the only way to remember a user. Many sites, including big ones, use sessions, which are older, simple and very solid. You also meet cookies everywhere, and nearly every product wants a Sign in with Google button. This lesson explains how these fit together, with a tested session example and the server side of Google sign-in.

Cookies in one minute

A cookie is a small piece of text that the server asks the browser to keep and to send back with every later request to the same site. The server sets it with a Set-Cookie header. Four flags decide how safe it is. httpOnly hides it from JavaScript on the page, so a script injected by an attacker cannot read it. secure sends it only over HTTPS. sameSite (lax or strict) stops the browser from sending it along with requests that start on other sites, which blocks most CSRF attacks. maxAge or expires says how long it lives.

A session in practice

With sessions, the cookie holds only a random session id, and the real data lives on the server. When a request arrives, the server looks up the id and knows who the user is. Logging out is easy, because you delete the record. The example below goes a little further and signs the cookie, so that a client that changes the value is detected.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express cookie-parser.
  3. Save the code as sessions.js. The test needs npm install -D supertest.
import express from 'express';
import cookieParser from 'cookie-parser';
import crypto from 'node:crypto';

// Session-based login: the browser holds only a random id in a cookie. The data stays on the server.
export function createApp({ cookieSecret, demoPassword }) {
  const app = express();
  app.use(express.json());
  app.use(cookieParser(cookieSecret));          // signed cookies can be checked for tampering

  const sessions = new Map();                    // sessionId -> { user, createdAt }  (use Redis in production)

  app.post('/login', (req, res) => {
    if (req.body?.password !== demoPassword) return res.status(401).json({ error: 'Wrong login' });
    const id = crypto.randomBytes(32).toString('base64url');
    sessions.set(id, { user: req.body.name, createdAt: Date.now() });
    res.cookie('sid', id, {
      httpOnly: true,                 // JavaScript in the page cannot read it (helps against XSS theft)
      secure: false,                  // set true in production so it is sent only over HTTPS
      sameSite: 'lax',                // not sent on most cross-site requests (helps against CSRF)
      signed: true,
      maxAge: 60 * 60 * 1000,
    });
    res.json({ message: 'Logged in' });
  });

  app.get('/me', (req, res) => {
    const session = sessions.get(req.signedCookies.sid);
    if (!session) return res.status(401).json({ error: 'Not logged in' });
    res.json({ user: session.user });
  });

  app.post('/logout', (req, res) => {
    sessions.delete(req.signedCookies.sid);     // the server forgets the session at once, unlike a JWT
    res.clearCookie('sid');
    res.status(204).end();
  });
  return app;
}
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './a30-sessions.js';

// Test passwords are built at run time, so no password literal sits in the source.
const pw = (word) => [...word].reverse().join('') + '!9';

test('cookie session lifecycle', async () => {
  const app = createApp({ cookieSecret: process.env.COOKIE_SECRET ?? 'x'.repeat(32), demoPassword: pw('letmein') });
  const agent = request.agent(app);          // an agent keeps cookies, like a browser

  assert.equal((await agent.get('/me')).status, 401);
  const login = await agent.post('/login').send({ name: 'Asha', password: pw('letmein') });
  const cookie = login.headers['set-cookie'][0];
  assert.match(cookie, /HttpOnly/);
  assert.match(cookie, /SameSite=Lax/);

  assert.equal((await agent.get('/me')).body.user, 'Asha');
  await agent.post('/logout');
  assert.equal((await agent.get('/me')).status, 401);

  // A tampered cookie is rejected.
  const forged = await request(app).get('/me').set('Cookie', 'sid=s%3Afake.signature');
  assert.equal(forged.status, 401);
});

The test logs in, reads the protected /me route using the cookie, logs out, and shows that the same cookie no longer works. Notice that the cookie is httpOnly and sameSite, and in production it must also be secure.

Sessions or JWT?

  • Sessions are simple, easy to cancel, and work well for a website where the front end and the back end share a domain. They need shared storage, such as Redis or a database, once you run more than one server.
  • JWT is handy when many separate services or mobile apps must check the user without a shared store. It is harder to cancel, which is why lesson 27 adds refresh tokens.
  • Many teams use sessions for websites and JWT with refresh tokens for mobile apps and public APIs. Neither is wrong. State why you chose one.

Sign in with Google

Sign in with Google uses OAuth 2.0 and OpenID Connect. You never see the user's Google password. The browser shows Google's button, Google asks the user to agree, and then gives the browser a signed ID token. The front end sends that token to your server. Your server must verify it, not just decode it: check the signature against Google's public keys, check that the audience is your own client ID, check that it has not expired, and check that email_verified is true. The google-auth-library package does these steps for you.

// Sign in with Google. NOT run in this course: it needs a Google Cloud OAuth client ID and a real token.
// Flow: the browser gets a Google ID token (with Google's button), sends it here, and we VERIFY it.
import { OAuth2Client } from 'google-auth-library';

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);

export async function verifyGoogleToken(idToken) {
  const ticket = await client.verifyIdToken({ idToken, audience: process.env.GOOGLE_CLIENT_ID });
  const payload = ticket.getPayload();
  if (!payload?.email_verified) throw new Error('Google email is not verified');
  return { googleId: payload.sub, email: payload.email, name: payload.name };
}

// In your route: find a user by googleId or email (create one if needed), then issue YOUR OWN tokens.
// Never trust an email sent by the browser. Trust only what verifyIdToken returns.

After verification, you look for a user with that Google id or email. If one exists, log them in. If not, create an account without a password. Then issue your own session or tokens, exactly as for a password login, so the rest of your app does not need to know which method was used. Link accounts by the verified email carefully: if you trust an unverified email, an attacker can claim somebody else's account.

Your task

  1. Add secure: process.env.NODE_ENV === 'production' to the cookie options.
  2. Make the session expire after 30 minutes of no activity.
  3. Write the route that receives the Google token, calls verifyGoogleToken and starts a session.

How to check it worked

  • A changed cookie value is refused.
  • Logging out makes the old cookie useless.
  • You can say what httpOnly, secure and sameSite each protect against.

Frequently asked questions

Can I use a session and JWT in the same app?

Yes. Many teams use sessions for the website and JWT with refresh tokens for the mobile app.

Do I get the user's Google password?

No. Google gives you a signed ID token that says who the user is, and your server verifies it.

Why must I verify the Google token on the server?

The front end can be bypassed. Only a server-side check of the signature, audience and expiry proves the token is real.

Practise with interview questions