RegisterLogin
DocsPricing
RegisterLogin
  • Getting Started
  • Introduction
  • Quick Start
  • SDKs
  • React
  • TypeScript
  • Next.js
  • Express
  • NestJS
  • Python
  • API Reference
  • Support and Resources
  • FAQ
  • Contact Support

AuthSafe

Product

HighlightFeatureIntegrationPricingFAQ

Company

AboutBlogContactSitemap

Developer

DashboardDocumentation

Legal

Terms & ConditionsPrivacyComplianceShippingCancellation

© 2026 AuthSafe. All rights reserved.

We value your privacy

This website uses cookies for anonymous analytics to help us improve your experience. No personal information is stored or shared. You can allow or reject analytics tracking at any time. See our Privacy Policy.

We use cookies for anonymous analytics. No personal info is stored. See our Privacy Policy.

Setup & Configuration

Complete setup guide for integrating AuthSafe authentication in Express.js applications.

Installation

npm install authsafe-express cookie-parser
yarn add authsafe-express cookie-parser
pnpm add authsafe-express cookie-parser
Required Dependencies
The SDK requires cookie-parser middleware for session management.

Environment Variables

Create a .env file in your project root:
# Required
AUTHSAFE_CLIENT_ID=your_client_id_here
AUTHSAFE_CLIENT_SECRET=your_client_secret_here
AUTHSAFE_DOMAIN=https://auth.yourapp.com

# Optional
APP_URL=http://localhost:3000
NODE_ENV=development
Keep Secrets Safe
Never commit your .env file to version control. Add it to .gitignore.

Basic Setup

1. Apply Cookie Parser

Cookie parser must be applied before AuthSafe middleware:
import express from 'express';
import cookieParser from 'cookie-parser';

const app = express();

// Required: Parse cookies
app.use(cookieParser());

2. Initialize AuthSafe

Call initAuthSafe() once during app initialization:
import { initAuthSafe } from 'authsafe-express';

initAuthSafe({
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: process.env.AUTHSAFE_DOMAIN!,
  redirectUri: `${process.env.APP_URL}/auth/callback`,
});

Configuration

AuthSafeConfig Interface

interface AuthSafeConfig {
  /** OAuth2 client ID from AuthSafe dashboard */
  clientId: string;

  /** OAuth2 client secret (required for token exchange) */
  clientSecret?: string;

  /** AuthSafe domain (e.g., 'https://auth.yourapp.com') */
  domain: string;

  /** Redirect URI after authentication */
  redirectUri?: string;

  /** Scopes to request (defaults to ['openid', 'email', 'profile']) */
  scopes?: string[];

  /** Cookie configuration */
  cookies?: {
    prefix?: string;
    domain?: string;
    path?: string;
    secure?: boolean;
    sameSite?: 'strict' | 'lax' | 'none';
  };

  /** Session configuration */
  session?: {
    maxAge?: number;
  };
}

Configuration Parameters

ParameterTypeRequiredDescription
clientIdstringYesOAuth2 client ID from dashboard
clientSecretstringNo*Required for token exchange and refresh
domainstringYesYour AuthSafe domain URL
redirectUristringNoCallback URL (defaults to /auth/callback)
scopesstring[]NoOAuth scopes to request

Advanced Configuration

Custom Scopes

initAuthSafe({
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: process.env.AUTHSAFE_DOMAIN!,
  scopes: [
    'openid',
    'email',
    'profile',
    'offline_access', // For refresh tokens
    'admin:read', // Custom scope
    'admin:write',
  ],
});

Cookie Configuration

initAuthSafe({
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: process.env.AUTHSAFE_DOMAIN!,
  cookies: {
    prefix: 'myapp', // Cookie name prefix
    domain: '.yourapp.com', // Cookie domain
    path: '/', // Cookie path
    secure: true, // HTTPS only
    sameSite: 'lax', // CSRF protection
  },
});

Session Duration

initAuthSafe({
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: process.env.AUTHSAFE_DOMAIN!,
  session: {
    maxAge: 7 * 24 * 60 * 60, // 7 days in seconds
  },
});

Complete Application Setup

import express from 'express';
import cookieParser from 'cookie-parser';
import {
  initAuthSafe,
  requireAuth,
  optionalAuth,
  handleSignIn,
  handleCallback,
  handleLogout,
  handleRefresh,
} from 'authsafe-express';

const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// Initialize AuthSafe
initAuthSafe({
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: process.env.AUTHSAFE_DOMAIN!,
  redirectUri: `${process.env.APP_URL}/auth/callback`,
  scopes: ['openid', 'email', 'profile', 'offline_access'],
  cookies: {
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
  },
  session: {
    maxAge: 24 * 60 * 60, // 24 hours
  },
});

// Auth routes
app.get('/auth/signin', (req, res) => {
  handleSignIn(req, res, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    domain: process.env.AUTHSAFE_DOMAIN!,
    redirectUri: `${process.env.APP_URL}/auth/callback`,
  });
});

app.get('/auth/callback', (req, res) => {
  handleCallback(req, res, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
    domain: process.env.AUTHSAFE_DOMAIN!,
    redirectUri: `${process.env.APP_URL}/auth/callback`,
  });
});

app.post('/auth/logout', (req, res) => {
  handleLogout(req, res, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    domain: process.env.AUTHSAFE_DOMAIN!,
  });
});

app.post('/auth/refresh', (req, res) => {
  handleRefresh(req, res, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
    domain: process.env.AUTHSAFE_DOMAIN!,
  });
});

// Public routes
app.get('/', (req, res) => {
  res.json({ message: 'Public home page' });
});

app.get('/about', optionalAuth(), (req, res) => {
  if (req.auth) {
    res.json({ message: `Hello ${req.auth.email}` });
  } else {
    res.json({ message: 'Hello guest' });
  }
});

// Protected routes
app.get('/dashboard', requireAuth(), (req, res) => {
  res.json({
    message: 'Dashboard',
    user: req.auth,
  });
});

// Error handling
app.use((err: any, req: any, res: any, next: any) => {
  console.error('Error:', err);
  res.status(500).json({ error: 'Internal server error' });
});

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

TypeScript Setup

Install Types

npm install -D @types/express @types/cookie-parser

Configure tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "lib": ["ES2022"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "moduleResolution": "node"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Type-Safe Request

import type { AuthenticatedRequest } from 'authsafe-express';

app.get('/profile', requireAuth(), (req: AuthenticatedRequest, res) => {
  // req.auth is fully typed
  const { userId, email, scopes, organizationId } = req.auth;

  res.json({
    userId,
    email,
    scopes,
    organizationId,
  });
});

Environment-Specific Configuration

Development

// config/development.ts
export const authConfig = {
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: 'http://localhost:8000',
  redirectUri: 'http://localhost:3000/auth/callback',
  cookies: {
    secure: false, // Allow HTTP in dev
    sameSite: 'lax' as const,
  },
};

Production

// config/production.ts
export const authConfig = {
  clientId: process.env.AUTHSAFE_CLIENT_ID!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET!,
  domain: process.env.AUTHSAFE_DOMAIN!,
  redirectUri: process.env.REDIRECT_URI!,
  cookies: {
    secure: true, // HTTPS only
    sameSite: 'lax' as const,
    domain: '.yourapp.com',
  },
  session: {
    maxAge: 7 * 24 * 60 * 60, // 7 days
  },
};

Load Config

import { authConfig } from `./config/${process.env.NODE_ENV}`;
import { initAuthSafe } from 'authsafe-express';

initAuthSafe(authConfig);

Troubleshooting

Cookies Not Set

Ensure cookie-parser is applied before AuthSafe routes:
app.use(cookieParser()); // ✅ Before auth routes

app.get('/auth/callback', handleCallback);

HTTPS Required Error

In production, enable secure cookies:
initAuthSafe({
  // ...
  cookies: {
    secure: true, // Requires HTTPS
  },
});

CORS Issues

Configure CORS for cross-origin requests:
import cors from 'cors';

app.use(
  cors({
    origin: process.env.FRONTEND_URL,
    credentials: true, // Allow cookies
  }),
);

Best Practices

  1. Use environment variables for all sensitive configuration
  2. Enable secure cookies in production (HTTPS only)
  3. Set appropriate session duration based on security requirements
  4. Use custom scopes for fine-grained access control
  5. Implement error handling for auth failures
  6. Add logging for debugging auth issues
  7. Test locally before deploying to production

Related

  • Middleware - Authentication and authorization
  • Route Handlers - OAuth flow handlers
  • Session Management - Cookie management
  • Express SDK Overview - Back to overview