Skip to main content

requireAuth()

Type: RequestHandler Access: nauth.helpers.requireAuth()

Express middleware that protects routes by requiring valid authentication.

Signature

requireAuth(options?: RequireAuthOptions): RequestHandler

Options

OptionTypeDefaultDescription
csrfbooleantrueValidate CSRF token

Overview

The requireAuth() helper enforces authentication for routes. It returns 401 if the user is not authenticated and validates CSRF tokens when using cookie-based token delivery.

Key Features:

  • Returns 401 if not authenticated
  • Validates CSRF token by default
  • Can skip CSRF validation for specific routes
  • Works with auth middleware

Usage

Basic Usage

Protect a route with authentication:

import express from 'express';
import { NAuth, ExpressAdapter } from '@nauth-toolkit/core';

const app = express();
const nauth = await NAuth.create({
config: authConfig,
dataSource,
adapter: new ExpressAdapter(),
});

app.get('/profile', nauth.helpers.requireAuth(), async (req, res) => {
const user = nauth.helpers.getCurrentUser();
res.json({ user });
});

Skip CSRF Validation

Skip CSRF validation for specific routes (e.g., logout):

// Logout uses GET to avoid CSRF issues
app.get('/auth/logout', nauth.helpers.requireAuth({ csrf: false }), async (req, res) => {
await nauth.authService.logout({ session: req.session?.id });
res.json({ success: true });
});

Protected API Endpoints

app.post('/api/posts', nauth.helpers.requireAuth(), async (req, res) => {
const user = nauth.helpers.getCurrentUser();
const post = await postsService.create(user.sub, req.body);
res.json(post);
});

app.delete('/api/posts/:id', nauth.helpers.requireAuth(), async (req, res) => {
const user = nauth.helpers.getCurrentUser();
await postsService.delete(req.params.id, user.sub);
res.json({ success: true });
});

Errors

CodeStatusWhen
UNAUTHORIZED401No valid token
CSRF_INVALID403CSRF validation failed

Error Response Example:

{
"statusCode": 401,
"message": "Authentication required",
"error": "Unauthorized",
"code": "AUTH_REQUIRED"
}