This document covers the middleware pipeline, request processing flow, and HTTP layer architecture in the VTEX Rewriter application.
📋 Table of Contents
🔄 Pipeline Overview
Application Layers
_19┌─────────────────────────────────────────────────────────────────┐_19│ HTTP Layer │_19├─────────────────────────────────────────────────────────────────┤_19│ Middleware Pipeline │_19│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │_19│ │ Error │→│ Auth │→│ Cache │→│ Init │→│ ... │ │_19│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │_19├─────────────────────────────────────────────────────────────────┤_19│ Route Resolution │_19│ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │_19│ │ Redirects │ │ Internals │ │ Compatibility│ │_19│ └─────────────┘ └─────────────┘ └──────────────┘ │_19├─────────────────────────────────────────────────────────────────┤_19│ Data Layer │_19│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │_19│ │ VBase │ │ Catalog │ │ Proxy │ │_19│ │ (Storage) │ │ (API) │ │ (Render) │ │_19│ └─────────────┘ └─────────────┘ └─────────────┘ │_19└─────────────────────────────────────────────────────────────────┘
🔄 Complete Request Flow
Complete Request Processing Flow
🔄 Detailed Middleware Pipeline
1. Error Middleware
_14// Captures errors and converts to appropriate HTTP responses_14try {_14 await next()_14} catch (error) {_14 if (error instanceof ExpiredUserError) {_14 // Redirect to login_14 ctx.redirect(`/login?returnUrl=$\{encodeURIComponent(ctx.path)\}`)_14 } else if (error instanceof UnauthorizedError) {_14 ctx.status = 401_14 } else {_14 ctx.status = 500_14 ctx.body = { error: error.message }_14 }_14}
2. Authorization Middleware
_10// Validates tokens and permissions_10const authToken = ctx.get('VtexIdclientAutCookie')_10if (authToken) {_10 const user = await vtexId.getUser(authToken)_10 ctx.vtex.user = user_10}
3. Cache Middleware
_20// Implements response caching with TTL_20const cacheKey = `$\{ctx.method\}:$\{ctx.path\}:$\{binding.id\}`_20const cached = await cache.get(cacheKey)_20_20if (cached && !cached.expired) {_20 ctx.body = cached.data_20 ctx.status = cached.status_20 return_20}_20_20await next()_20_20// Cache response if status 2xx_20if (ctx.status >= 200 && ctx.status < 300) {_20 await cache.set(cacheKey, {_20 data: ctx.body,_20 status: ctx.status,_20 ttl: getTTL(ctx.path)_20 })_20}
4. Initialize Middleware
_10// Sets up context and resources_10ctx.state.settings = await apps.getAppSettings('vtex.rewriter')_10ctx.resources = {_10 internals: new Internals(ctx),_10 redirects: new Redirects(ctx)_10}
5. Enforce URL Middleware
_12// Applies normalization rules_12const { enforceLowerCaseUrls, enforceNoEndingSlashUrls } = settings_12_12if (enforceLowerCaseUrls && hasUpperCase(ctx.path)) {_12 ctx.redirect(ctx.path.toLowerCase(), 301)_12 return_12}_12_12if (enforceNoEndingSlashUrls && ctx.path.endsWith('/')) {_12 ctx.redirect(ctx.path.slice(0, -1), 301)_12 return_12}