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 need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| Provider account | e.g. Google Cloud console for Google sign-in |
| Basics | HTTP redirects, cookies/sessions |
3. Local setup
1Understand the flow
Four parties take part: user, your app (client), the authorization server and the API (resource server).
OUTPUT1. 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 user2Register 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 URIhttp://localhost:3000/auth/callback, then copy the client ID and secret.3Create the project
express-session keeps
stateand the PKCE verifier between redirect and callback.BASHmkdir oauth-demo && cd oauth-demo npm init -y && npm pkg set type=module npm install express express-session
4. Create & run a project
1Start the login
Generate
state(CSRF protection) and a PKCE verifier/challenge, save them in the session and redirect.server.jsimport 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); });2Handle the callback
Verify
state, exchange the code for tokens, then fetch the user profile.JSapp.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'));3Run it
Open http://localhost:3000 and click the link.
BASHnode --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.
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-valueKey dependencies
| Package / tool | Used for |
|---|---|
express-session (+ a store such as connect-redis) | Keeps state/verifier and the logged-in user |
openid-client / Auth.js / Passport | Libraries that implement OAuth/OIDC fully (discovery, ID-token validation) |
Keycloak / Auth0 / Cognito | Run or rent your own authorization server |
Folder structure
oauth-demo/
├── server.js # /login, /auth/callback, /logout
├── .env # client id/secret, redirect URI
└── package.jsonEssential commands
| Command | What it does |
|---|---|
node --env-file=.env server.js | Start the demo |
curl https://accounts.google.com/.well-known/openid-configuration | See Google’s OIDC endpoints (discovery document) |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| HTTPS | Required for production redirect URIs |
| Exact redirect URIs | Registered for every environment (staging, production) |
| Secret storage | Client secret in env/secret manager only |
| Session store | Redis or DB when running several instances |
| Consent screen | Published (and verified, if you request sensitive scopes) |
Deployment steps
1Register production redirect URIs
Add
https://example.com/auth/callbackto the OAuth client, and set the app’s authorised domains on the consent screen. Publish the consent screen when ready.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.
JSapp.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 }), }));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.
BASHssh 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_IP4Install 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.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v5Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/oauth-demo cd /var/www/oauth-demo npm ci --omit=dev nano .env # production values6Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo 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 deploy7Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { 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"; } }8Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx9Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status10Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com11Add 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.BASHsudo 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.
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.