Node.js FusionAuth Quickstart

A complete Node.js/Express application demonstrating FusionAuth integration with OAuth 2.0, JWT validation, and user management

Overview

This quickstart guide demonstrates how to integrate FusionAuth with a Node.js/Express application. The example includes complete authentication flows, session management, and protected routes.

🚀 Quick Setup

Get up and running in under 5 minutes with our streamlined configuration process

🔒 Secure by Default

Production-ready security configurations including PKCE, JWT validation, and CSRF protection

📝 Complete Example

Full authentication flow including login, logout, registration, and protected routes

Installation

Terminal
# Clone the repository
git clone https://github.com/JustinArndtAI/AIgent.git
cd AIgent/example-apps/node-quickstart

# Install dependencies
npm install

# Configure environment variables
cp .env.example .env
# Edit .env with your FusionAuth configuration

# Start the application
npm start

Key Implementation

index.js
const express = require('express');
const session = require('express-session');
const { FusionAuthClient } = require('@fusionauth/node-client');

const app = express();
const client = new FusionAuthClient(
  process.env.FUSIONAUTH_API_KEY,
  process.env.FUSIONAUTH_URL
);

// Configure session middleware
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: process.env.NODE_ENV === 'production',
    httpOnly: true,
    maxAge: 3600000 // 1 hour
  }
}));

// OAuth 2.0 login route
app.get('/login', (req, res) => {
  const authorizeUrl = `${process.env.FUSIONAUTH_URL}/oauth2/authorize?` +
    `client_id=${process.env.CLIENT_ID}&` +
    `redirect_uri=${encodeURIComponent(process.env.REDIRECT_URI)}&` +
    `response_type=code&` +
    `scope=openid profile email`;
  
  res.redirect(authorizeUrl);
});

// OAuth callback handler
app.get('/oauth-callback', async (req, res) => {
  const { code } = req.query;
  
  try {
    // Exchange authorization code for tokens
    const tokenResponse = await client.exchangeOAuthCodeForAccessToken(
      code,
      process.env.CLIENT_ID,
      process.env.CLIENT_SECRET,
      process.env.REDIRECT_URI
    );
    
    // Store user info in session
    req.session.user = tokenResponse.response.user;
    req.session.token = tokenResponse.response.access_token;
    
    res.redirect('/dashboard');
  } catch (error) {
    console.error('OAuth callback error:', error);
    res.redirect('/login?error=authentication_failed');
  }
});

// Protected route middleware
function requireAuth(req, res, next) {
  if (!req.session.user) {
    return res.redirect('/login');
  }
  next();
}

// Protected dashboard route
app.get('/dashboard', requireAuth, (req, res) => {
  res.json({
    message: 'Welcome to your dashboard!',
    user: req.session.user
  });
});

// Logout route
app.post('/logout', (req, res) => {
  req.session.destroy();
  res.redirect('/');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Configuration

Configure your FusionAuth application with these settings:

.env
# FusionAuth Configuration
FUSIONAUTH_URL=http://localhost:9011
FUSIONAUTH_API_KEY=your-api-key-here
CLIENT_ID=your-client-id-here
CLIENT_SECRET=your-client-secret-here
REDIRECT_URI=http://localhost:3000/oauth-callback

# Session Configuration  
SESSION_SECRET=your-session-secret-here
NODE_ENV=development
PORT=3000

Features

Next Steps