Overview
Ship uses middlewares for authentication, error handling, and request processing. Middlewares are applied in two ways:- Global Middlewares — Run for all routes in a specific order
- Route-Specific Middlewares — Applied only to private or admin routes
Execution Order
Global Middlewares
1. attachCustomErrors
Adds custom error handling methods to the context (ctx).
Available methods:
2. attachCustomProperties
Initializesctx.validatedData = {} which is later populated by the validate middleware.
3. routeErrorHandler
Catches and formats errors from route handlers. Logs errors with request context and hides sensitive details in production. Error response format:4. extractTokens
Extracts access tokens from requests and stores inctx.state.accessToken.
Token sources (checked in order):
ACCESS_TOKENcookieAuthorization: Bearer <token>header
5. tryToAttachUser
Validates the access token and attaches the user toctx.state.user if valid. Also updates the user’s last request timestamp.
This middleware doesn’t block requests if the token is invalid. Use the
auth middleware to enforce authentication.Route-Specific Middlewares
Applied to specific route types for authentication and authorization.auth
Ensures user is authenticated by checking ifctx.state.user exists. Returns 401 if not authenticated.
Usage:
adminAuth
Validates admin access by checking thex-admin-key header against the ADMIN_KEY environment variable. Returns 401 if invalid.
Usage:
Summary
Execution order:attachCustomErrors- Adds error methodsattachCustomProperties- Initializes propertiesrouteErrorHandler- Wraps in error handlerextractTokens- Extracts token from cookie/headertryToAttachUser- Validates token, attaches userauthoradminAuth(if applicable)- Route handler
See Also
- Routing - Routing architecture overview
- Middlewares - Validation and rate limiting
- API Actions - Creating resource endpoints
