Skip to main content

Quickstart Guide

This guide walks you through adding Google OAuth authentication to an existing Node.js project using Devark. You’ll go from zero to a working OAuth flow in about 5 minutes.

Prerequisites

Before starting, make sure you have:
  • Node.js 18+ installed
  • An existing Node.js project with package.json
  • An Express.js app (or similar entry file like app.js)
  • Devark installed (see Installation)
Don’t have a project yet? Create one quickly:
mkdir my-backend && cd my-backend
npm init -y
npm install express
touch app.js

Step-by-Step Tutorial

1

Navigate to your project

Open your terminal and navigate to your Node.js project directory:
cd /path/to/your/project
Verify you have a package.json file:
ls package.json
2

Run the Devark command

Execute the command to add Google OAuth:
devark add google-oauth
You’ll see the Devark logo and initialization message:
┌  Google OAuth Module Setup

○  Installing Google OAuth module...
│  ✓ pnpm detected
3

Choose JavaScript or TypeScript

Devark will ask which language you want to use:
◆  Which version do you want to add for this module?
│  ● JavaScript
│  ○ TypeScript
Use arrow keys to select and press Enter. For this guide, we’ll choose JavaScript.
4

Specify your entry file

Enter the path to your main application file:
◆  Enter your project entry file (relative to root):
│  app.js
Press Enter to use the default (app.js) or type your custom path (e.g., src/index.js).
5

Provide Google OAuth credentials

Devark will prompt for your Google OAuth credentials. You can skip these for now and add them later:
◆  Enter your Google Client ID (leave empty for sample):

└  Press Enter to skip

◆  Enter your Google Client Secret (leave empty for sample):

└  Press Enter to skip

◆  Enter your Google Callback URL:
│  http://localhost:3000/auth/google/callback
└  Press Enter to use default

◆  Enter your session secret (leave empty for sample):

└  Press Enter to skip
Don’t have credentials yet? No problem! Devark will use placeholder values. You can get real credentials from the Google Cloud Console later.
6

Wait for installation

Devark will now install dependencies and generate code:
◒  Installing dependencies...
This installs:
  • express
  • passport
  • passport-google-oauth20
  • express-session
  • dotenv
Output:
✓  Dependencies installed successfully.
✓  .env created with sample values.

└  Google OAuth setup complete!
7

Review generated files

Devark has created several files in your project:
your-project/
├── app.js                    # ← Modified with OAuth setup
├── .env                      # ← Created with credentials
├── config/
│   └── googleStrategy.js     # ← Passport Google strategy
└── routes/
    └── googleAuthRoutes.js   # ← OAuth routes
Let’s examine what was added:app.js - Updated with middleware and route registration:
import 'dotenv/config';
import session from 'express-session';
import passport from 'passport';
import googleAuthRoutes from './routes/googleAuthRoutes.js';
import './config/googleStrategy.js';

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

app.use('/', googleAuthRoutes);
.env - Environment variables for configuration:
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
SESSION_SECRET=your-session-secret
8

Configure Google OAuth credentials

To make OAuth work, you need real credentials from Google Cloud:
  1. Go to Google Cloud Console
  2. Create a new project or select existing one
  3. Navigate to APIs & Services → Credentials
  4. Click Create Credentials → OAuth 2.0 Client ID
  5. Configure the consent screen if prompted
  6. Select Web application as application type
  7. Add authorized redirect URI:
    http://localhost:3000/auth/google/callback
    
  8. Copy the Client ID and Client Secret
Update your .env file with the real credentials:
GOOGLE_CLIENT_ID=1234567890-abc123def456.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=GOCSPX-aBcDeFgHiJkLmNoPqRsTuVwXyZ
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
SESSION_SECRET=your-secure-random-string
Never commit your .env file to version control. Add it to .gitignore:
echo ".env" >> .gitignore
9

Start your application

Run your Express.js application:
node app.js
If you have a start script in package.json:
npm start
You should see:
Server listening on port 3000
10

Test the OAuth flow

Open your browser and navigate to:
http://localhost:3000/auth/google
You should be redirected to Google’s login page. After signing in, Google will redirect you back to your callback URL.The generated routes provide these endpoints:
  • GET /auth/google - Initiates OAuth flow
  • GET /auth/google/callback - Handles OAuth callback
  • GET /auth/logout - Logs out the user
  • GET /auth/profile - Returns user profile (if authenticated)
Test the profile endpoint after logging in:
curl http://localhost:3000/auth/profile
Expected response:
{
  "id": "1234567890",
  "displayName": "John Doe",
  "emails": [{ "value": "[email protected]" }]
}

Understanding the Generated Code

Passport Strategy (config/googleStrategy.js)

This file configures Passport.js with the Google OAuth strategy:
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/auth/google/callback'
  },
  (accessToken, refreshToken, profile, done) => {
    // Here you can save user to database
    return done(null, profile);
  }
));

passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));

Auth Routes (routes/googleAuthRoutes.js)

Provides ready-to-use OAuth endpoints:
import express from 'express';
import passport from 'passport';

const router = express.Router();

// Initiate Google OAuth
router.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

// OAuth callback
router.get('/auth/google/callback',
  passport.authenticate('google', {
    failureRedirect: '/auth/failure',
    successRedirect: '/success'
  })
);

// Success page
router.get('/success', (req, res) => {
  const user = req.user;
  if (user) {
    res.send(`<h1>✅ Logged In Successfully</h1><p>Welcome, ${user.displayName}!</p>`);
  }
});

// Failure route
router.get('/auth/failure', (req, res) => {
  res.send('Failed to authenticate.');
});

export default router;

Customizing the Integration

The generated code is fully editable. Common customizations:

Save users to database

Modify config/googleStrategy.js:
(accessToken, refreshToken, profile, done) => {
  User.findOrCreate({ googleId: profile.id }, (err, user) => {
    return done(err, user);
  });
}

Add authentication middleware

Create middleware to protect routes:
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/login');
}

router.get('/dashboard', ensureAuthenticated, (req, res) => {
  res.render('dashboard', { user: req.user });
});

Customize redirect URLs

Edit the callback route in routes/googleAuthRoutes.js:
router.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => {
    // Redirect to dashboard instead of home
    res.redirect('/dashboard');
  }
);

Troubleshooting

”Redirect URI mismatch” error

Ensure the callback URL in Google Cloud Console exactly matches your .env file:
http://localhost:3000/auth/google/callback
No trailing slashes, correct port number.

”Invalid client” error

Double-check your GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in .env. Make sure there are no extra spaces.

Session not persisting

Ensure express-session is configured before passport.initialize():
app.use(session({ ... }));  // Must come first
app.use(passport.initialize());
app.use(passport.session());

Next Steps

Congratulations! You’ve successfully added Google OAuth to your project. Here are some ideas for next steps:

Add GitHub OAuth

devark add github-oauth

Add Email OTP

devark add resend-otp

Create New Project

devark add node-mongo

Explore TypeScript

Run any module with TypeScript support

Available Modules

Explore all available Devark modules:
  • devark add google-oauth - Google OAuth 2.0
  • devark add github-oauth - GitHub OAuth
  • devark add resend-otp - Email OTP via Resend
  • devark add node-mongo - Node.js + MongoDB template
  • devark add node-postgres - Node.js + PostgreSQL template
  • devark add oauth - Interactive OAuth provider selector
Each module supports both JavaScript and TypeScript. You’ll be prompted to choose during installation.

Build docs developers (and LLMs) love