API & Authentication

OAuth 2.0 Setup & Deployment Guide

“Login with Google” and secure delegated access – the Authorization Code flow with PKCE, step by step, from client registration to production.

Updated Official documentation ↗

1. Introduction & use cases

OAuth 2.0 is the standard for letting an app access resources on a user’s behalf without seeing their password. The user signs in at the authorization server (Google, Microsoft, GitHub, or your own Keycloak/Auth0), approves access, and your app receives tokens.

For web and mobile apps the recommended flow is Authorization Code with PKCE. OpenID Connect (OIDC) adds an ID token and user-info endpoint on top of OAuth 2.0, which is what “Login with Google” uses.

Where it is used

  • “Login with Google / Microsoft / GitHub” buttons
  • Accessing user data in other services (Google Drive, calendars)
  • Single sign-on across company apps
  • Machine-to-machine access with the client-credentials flow

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
Provider accounte.g. Google Cloud console for Google sign-in
BasicsHTTP redirects, cookies/sessions

3. Local setup

  1. 1Understand the flow

    Four parties take part: user, your app (client), the authorization server and the API (resource server).

    OUTPUT
    1. App redirects the user to the provider with client_id, redirect_uri, scope,
       state and a PKCE code_challenge
    2. User signs in and approves
    3. Provider redirects back to redirect_uri?code=...&state=...
    4. App checks state, then exchanges code + code_verifier (+ client secret)
       for tokens at the token endpoint
    5. App uses the access token / ID token to identify the user
  2. 2Register an OAuth client (Google example)

    In the Google Cloud console: create a project → Google Auth Platform / OAuth consent screen (app name, support email, scopes openid email profile) → Clients → Create client → Web application. Add the authorised redirect URI http://localhost:3000/auth/callback, then copy the client ID and secret.

  3. 3Create the project

    express-session keeps state and the PKCE verifier between redirect and callback.

    BASH
    mkdir oauth-demo && cd oauth-demo
    npm init -y && npm pkg set type=module
    npm install express express-session

4. Create & run a project

  1. 1Start the login

    Generate state (CSRF protection) and a PKCE verifier/challenge, save them in the session and redirect.

    server.js
    import express from 'express';
    import session from 'express-session';
    import crypto from 'node:crypto';
    
    const app = express();
    app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
    const { GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, REDIRECT_URI } = process.env;
    const b64url = (buf) => buf.toString('base64url');
    
    app.get('/login', (req, res) => {
      const state = b64url(crypto.randomBytes(16));
      const verifier = b64url(crypto.randomBytes(32));
      const challenge = b64url(crypto.createHash('sha256').update(verifier).digest());
      Object.assign(req.session, { state, verifier });
      const url = new URL('https://accounts.google.com/o/oauth2/v2/auth');
      url.search = new URLSearchParams({
        client_id: GOOGLE_CLIENT_ID, redirect_uri: REDIRECT_URI, response_type: 'code',
        scope: 'openid email profile', state, code_challenge: challenge, code_challenge_method: 'S256',
      });
      res.redirect(url);
    });
  2. 2Handle the callback

    Verify state, exchange the code for tokens, then fetch the user profile.

    JS
    app.get('/auth/callback', async (req, res) => {
      if (!req.query.code || req.query.state !== req.session.state) return res.status(400).send('Invalid state');
      const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          code: req.query.code, client_id: GOOGLE_CLIENT_ID, client_secret: GOOGLE_CLIENT_SECRET,
          redirect_uri: REDIRECT_URI, grant_type: 'authorization_code', code_verifier: req.session.verifier,
        }),
      });
      const tokens = await tokenRes.json();
      if (!tokenRes.ok) return res.status(401).json(tokens);
      const me = await (await fetch('https://openidconnect.googleapis.com/v1/userinfo', {
        headers: { Authorization: `Bearer ${tokens.access_token}` },
      })).json();
      req.session.regenerate(() => { req.session.user = { id: me.sub, email: me.email, name: me.name }; res.redirect('/'); });
    });
    
    app.get('/', (req, res) => res.send(req.session.user ? `Hello ${req.session.user.name}` : '<a href="/login">Login with Google</a>'));
    app.listen(3000, () => console.log('http://localhost:3000'));
  3. 3Run it

    Open http://localhost:3000 and click the link.

    BASH
    node --env-file=.env server.js

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

The redirect URI must match exactly (scheme, host, port, path) what you registered with the provider.

.env
GOOGLE_CLIENT_ID=1234567890-abc.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=paste-from-console
REDIRECT_URI=http://localhost:3000/auth/callback
SESSION_SECRET=long-random-value

Key dependencies

Package / toolUsed for
express-session (+ a store such as connect-redis)Keeps state/verifier and the logged-in user
openid-client / Auth.js / PassportLibraries that implement OAuth/OIDC fully (discovery, ID-token validation)
Keycloak / Auth0 / CognitoRun or rent your own authorization server

Folder structure

project structure
oauth-demo/
├── server.js     # /login, /auth/callback, /logout
├── .env          # client id/secret, redirect URI
└── package.json

Essential commands

CommandWhat it does
node --env-file=.env server.jsStart the demo
curl https://accounts.google.com/.well-known/openid-configurationSee Google’s OIDC endpoints (discovery document)

6. Production deployment

Server & hosting requirements

RequirementRecommendation
HTTPSRequired for production redirect URIs
Exact redirect URIsRegistered for every environment (staging, production)
Secret storageClient secret in env/secret manager only
Session storeRedis or DB when running several instances
Consent screenPublished (and verified, if you request sensitive scopes)

Deployment steps

  1. 1Register production redirect URIs

    Add https://example.com/auth/callback to the OAuth client, and set the app’s authorised domains on the consent screen. Publish the consent screen when ready.

  2. 2Use secure cookies and a shared session store

    Behind Nginx trust the proxy, mark cookies secure, and store sessions in Redis so all instances share them.

    JS
    app.set('trust proxy', 1);
    app.use(session({
      secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false,
      cookie: { secure: true, httpOnly: true, sameSite: 'lax' },
      // store: new RedisStore({ client: redisClient }),
    }));
  3. 3Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  4. 4Install Node.js on the server

    Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  5. 5Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/oauth-demo
    cd /var/www/oauth-demo
    npm ci --omit=dev
    nano .env   # production values
  6. 6Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo npm install -g pm2
    pm2 start server.js --name oauth-demo --node-args="--env-file=.env"
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs oauth-demo        # live logs
    pm2 restart oauth-demo     # after each deploy
  7. 7Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  8. 8Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  9. 9Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  10. 10Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  11. 11Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ node --env-file=.env server.jshttp://localhost:3000GET /login 302 → accounts.google.com/o/oauth2/v2/auth?...GET /auth/callback?code=4/0Ab...&state=... 302 → /GET / 200 "Hello Asha Verma"
Figure 1: terminal output of the sample OAuth 2.0 project (section 4).
1Redirect + PKCE2User approves atprovider3Callback with code4Exchange code →tokens5Session on HTTPS
Figure 2: production deployment flow (section 6).
oauth-demo/├── server.js # /login, /auth/callback, /logout├── .env # client id/secret, redirect URI└── package.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Error 400: redirect_uri_mismatch

The URI sent by your app is not registered exactly. Copy it from the error details into the console (http vs https, trailing slash, port).

invalid_grant when exchanging the code

The code was used twice, expired (they live about a minute), or the code_verifier/redirect URI differs from the first request.

“Invalid state” on callback

The session was lost (cookie not sent, different domain, server restarted with in-memory sessions). Use a persistent session store and the same domain.

access_denied

The user cancelled, or the app is in testing mode and the user is not on the test-user list.

“This app isn’t verified” warning

Google shows it for unverified apps requesting sensitive scopes. Request only openid email profile or complete verification.

Best practices

  • Always use PKCE and a random state.
  • Request the fewest scopes you need.
  • Validate ID tokens (issuer, audience, expiry) – use a certified library in production.
  • Regenerate the session after login to prevent session fixation.
  • Never put the client secret in front-end code.