🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@fluojs/http

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@fluojs/http

HTTP execution layer — routing, guards, interceptors, DTO binding, and exception handling for Fluo.

Source
npmnpm
Version
1.0.0-beta.8
Version published
Weekly downloads
85
-82.86%
Maintainers
1
Weekly downloads
 
Created
Source

@fluojs/http

English 한국어

The HTTP execution layer that turns route metadata into a request pipeline with binding, validation, guards, interceptors, and response writing.

Table of Contents

Installation

npm install @fluojs/http

When to Use

Use this package when you need to:

  • define REST-style controllers with decorators such as @Controller, @Get, and @Post
  • bind request data into DTOs with @FromBody, @FromPath, @FromQuery, and related decorators
  • run guards, interceptors, and middleware in a predictable request lifecycle
  • access the active request through RequestContext without passing it through every function

Quick Start

import { Controller, FromBody, FromPath, Get, Post, RequestDto } from '@fluojs/http';
import { IsString, MinLength } from '@fluojs/validation';

class CreateUserDto {
  @FromBody()
  @IsString()
  @MinLength(3)
  name!: string;
}

@Controller('/users')
export class UserController {
  @Post('/')
  @RequestDto(CreateUserDto)
  create(input: CreateUserDto) {
    return { id: '1', name: input.name };
  }

  @Get('/:id')
  getById(@FromPath('id') id: string) {
    return { id, name: 'John Doe' };
  }
}

Route path contract

HTTP route decorators such as @Controller(), @Get(), and @Post() accept only:

  • literal path segments like /users or /healthz
  • full-segment path params like /:id or /users/:userId/posts/:postId

Trailing slashes and duplicate slashes are normalized during route mapping, so //users///:id/ resolves to /users/:id.

Route decorators do not support wildcard, regex-like, or mixed-segment syntax such as *, ?, /(.*), user-:id, or :id.json. Wildcard matching remains middleware-only via forRoutes('/users/*').

Common Patterns

Guards and interceptors

import { Controller, Get, UseGuards, UseInterceptors } from '@fluojs/http';

@Controller('/admin')
@UseGuards(AdminGuard)
@UseInterceptors(LoggingInterceptor)
class AdminController {
  @Get('/')
  dashboard() {
    return { data: 'secret' };
  }
}

Async request context

import { getCurrentRequestContext } from '@fluojs/http';

function someDeepHelper() {
  const ctx = getCurrentRequestContext();
  console.log(ctx?.requestId);
}

Rate limiting behind proxies

createRateLimitMiddleware(...) resolves client identity from the raw socket remoteAddress by default. To trust Forwarded, X-Forwarded-For, or X-Real-IP, opt in with trustProxyHeaders: true only when your adapter sits behind a trusted proxy that overwrites those headers. If your adapter exposes neither a trusted proxy chain nor a raw socket identity, provide an explicit keyResolver.

Server-sent events

import { Get, SseResponse, type RequestContext } from '@fluojs/http';

@Get('/events')
stream(_input: undefined, ctx: RequestContext) {
  const sse = new SseResponse(ctx);
  sse.send({ message: 'hello' });
  return sse;
}

Request Cleanup and Portability

The dispatcher binds RequestContext with AsyncLocalStorage for the active dispatch only. When a request may use request-scoped DI through its controller graph, middleware, guards, interceptors, observers, DTO converters, a custom binder, or manual getCurrentRequestContext() / assertRequestContext() container access, the dispatcher creates and disposes an isolated request-scoped DI container from its finally path after request observers finish. Singleton-only routes skip that container lifecycle until RequestContext.container is accessed, so the baseline path avoids unnecessary per-request allocation while preserving request-scoped provider isolation whenever the graph is ambiguous or request-scoped. Public RequestContext.container reads are therefore always safe for resolving request-scoped providers; the singleton-only fast path is an internal dispatcher optimization, not a promise that the public context exposes the root container.

Adapters should pass an AbortSignal on FrameworkRequest.signal when the platform exposes one. For SSE, adapters should also expose FrameworkResponse.stream.onClose(...) when possible; SseResponse listens to both request abort and raw stream close, closes idempotently, and removes registered listeners when either side terminates first.

Public API

  • Routing decorators: Controller, Get, Post, Put, Patch, Delete, All, Options, Head
  • Binding decorators: FromBody, FromQuery, FromPath, FromHeader, FromCookie, RequestDto, Optional, Convert
  • Execution decorators: UseGuards, UseInterceptors, HttpCode, Version, Header, Redirect, Produces
  • Core runtime types: RequestContext, FrameworkRequest, FrameworkResponse, SseResponse
  • Exceptions: BadRequestException, UnauthorizedException, ForbiddenException, NotFoundException, InternalServerErrorException, PayloadTooLargeException
  • Helpers: createHandlerMapping, createDispatcher, forRoutes, normalizeRoutePattern, matchRoutePattern, isMiddlewareRouteConfig, createCorrelationMiddleware, createCorsMiddleware, createRateLimitMiddleware, createSecurityHeadersMiddleware, getCurrentRequestContext, encodeSseComment, encodeSseMessage

Internal Subpath (@fluojs/http/internal)

The ./internal subpath exports only the low-level utilities used by platform adapters and the core runtime. These are subject to change and should not be used in typical application code.

  • DefaultBinder: Default DTO/request binder used by the runtime bootstrap path.
  • bindRawRequestNativeRouteHandoff(...) / attachFrameworkRequestNativeRouteHandoff(...): Internal adapter/runtime helpers for reusing semantically safe native route matches without widening the public dispatcher API.
  • Native route handoffs snapshot the framework request method and path when attached; if app middleware rewrites either value before handler matching, the dispatcher ignores the stale handoff and falls back to normal route matching.
  • isRoutePathNormalizationSensitive(path): Internal guard for keeping duplicate-slash and trailing-slash requests on the generic dispatcher path.
  • resolveClientIdentity(request): Conservative client identity resolver used by rate limiting and other runtime integrations.
  • @fluojs/core: stores controller, route, and DTO metadata
  • @fluojs/validation: validates DTOs after HTTP binding
  • @fluojs/runtime: assembles the dispatcher during application bootstrap
  • @fluojs/passport: plugs auth guards into the same HTTP guard chain

Example Sources

  • examples/realworld-api/src/users/create-user.dto.ts
  • examples/auth-jwt-passport/src/auth/auth.controller.ts
  • packages/http/src/dispatch/dispatcher.test.ts

Keywords

fluo

FAQs

Package last updated on 01 May 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts