Auth Routes
Create the authentication routes — set up the login route, the callback route, and the logout route that Passport.js will use.
Auth Routes
The OAuth flow requires specific routes: one to start the login process, one to handle the callback from Google, and one to log out. Let us create them.
The Auth Router
// routes/auth-routes.js
const router = require('express').Router();
// Auth login
router.get('/login', function(req, res) {
res.send('Login with Google');
});
// Auth logout
router.get('/logout', function(req, res) {
// TODO: handle logout
res.send('Logging out');
});
// Auth with Google
router.get('/google', function(req, res) {
// TODO: passport will handle this
res.send('Authenticating with Google...');
});
// Callback route for Google to redirect to
router.get('/google/redirect', function(req, res) {
// TODO: handle the callback
res.send('You reached the callback URI');
});
module.exports = router;
Registering Routes in app.js
// app.js
const express = require('express');
const authRoutes = require('./routes/auth-routes');
const app = express();
app.set('view engine', 'ejs');
// Set up routes
app.use('/auth', authRoutes);
app.get('/', function(req, res) {
res.render('home');
});
app.listen(3000, function() {
console.log('App listening on port 3000');
});
The Routes
| URL | Purpose |
|---|---|
/auth/google | Start the OAuth flow — redirect to Google |
/auth/google/redirect | Google redirects here after login — the callback |
/auth/logout | Log the user out and destroy the session |
Key Takeaways
/auth/googleinitiates the OAuth flow — Passport will handle the redirect/auth/google/redirectis the callback URL — Google sends the user back here- All auth routes are prefixed with
/authusingapp.use('/auth', authRoutes) - The callback URL must match exactly what you register in the Google Developer Console