Skip to content

HTTP Requests ​

Introduction ​

Every route handler and middleware receives a Request, an immutable value object that exposes everything about the incoming HTTP request: the method and URL, query string, headers, cookies, a parsed body, uploaded files, and the route parameters. This page shows every way to read that data.

ts
import { Request, Router } from '@plinthjs/http'

const router = new Router()
router.post('/posts', (req: Request) => ({ title: req.input('title') }))

For tests and scripts you can build a request by hand, no server required:

ts
const req = new Request({
  method: 'POST',
  url: '/api/posts?sort=desc',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  body: JSON.stringify({ title: 'Hello', published: 'yes' }),
  host: 'acme.test:8080',
})

method defaults to GET and url to /. Header names are lower-cased on the way in, so lookups are case-insensitive.

Method and path ​

ts
req.method() // => 'POST'
req.isMethod('post') // => true (case-insensitive)
req.path() // => '/api/posts' (no query string, no trailing slash)
req.url() // => '/api/posts?sort=desc' (path plus query)

Wildcard checks use * and ignore the leading slash:

ts
req.is('api/*') // => true
req.is('admin/*', 'api/*') // true if any pattern matches
req.routeIs('posts.*') // matches the name of the matched route
req.fullUrlIs('*/api/*')

routeIs() is false for unnamed routes. The kernel attaches the route name once it has matched.

Host, scheme and client address ​

ts
req.host() // => 'acme.test' (no port)
req.httpHost() // => 'acme.test:8080' (as sent)
req.isSecure() // => true over TLS (or a trusted X-Forwarded-Proto: https)
req.schemeAndHttpHost() // => 'https://acme.test:8080'
req.fullUrl() // => 'https://acme.test:8080/api/posts?sort=desc'
req.ip() // the client IP

req.ip() is the socket's remote address, which a client cannot forge. Plinth runs on plain node:http, so behind a TLS-terminating proxy it only believes X-Forwarded-For / X-Real-IP (client address), X-Forwarded-Proto (scheme, used by isSecure() and fullUrl()) and X-Forwarded-Host when the direct peer is a trusted proxy. Declare your proxies with the trustedProxies server option (true, a list of proxy IP addresses, or a predicate); see Running behind a proxy. With no trusted proxies the headers are ignored. req.ip() is undefined only for a synthetic request built without a remoteAddress.

To build variations of the current URL:

ts
req.fullUrlWithQuery({ page: 3 }) // => '.../api/posts?sort=desc&page=3'
req.fullUrlWithoutQuery(['sort']) // => '.../api/posts'

Query string ​

ts
req.query() // => { sort: 'desc', page: '2' }
req.query('sort') // => 'desc'
req.query('missing', 'fallback') // => 'fallback'

query() reads only the query string. Values are always strings.

Input ​

all() and input() read the merged input bag: query parameters overlaid with the parsed body, and the body wins on a conflict. The body is parsed according to Content-Type: JSON objects, application/x-www-form-urlencoded, and the text fields of multipart/form-data. Anything else leaves the bag with just the query.

ts
req.all() // every key
req.input('title') // => 'Hello'
req.input('missing', 'default') // => 'default'
req.only(['title', 'published']) // => { title: 'Hello', published: 'yes' }
req.except(['published']) // everything else
req.keys() // => ['sort', 'title', 'published']

input() (and has(), filled(), boolean(), integer() and the other typed readers) accept dot notation to reach into nested JSON or query data: req.input('user.address.city'), req.input('items.0.name'). A key that exists literally, dots included, always wins over the path reading.

URL-encoded bodies and query strings understand bracket syntax: a[b]=1 becomes { a: { b: '1' } } and c[]=3&c[]=4 becomes { c: ['3', '4'] }. req.query() and req.query('key') still return the raw flat pairs.

Checking presence ​

ts
req.has('title') // key exists, even if blank
req.filled('title') // key exists and is not blank
req.missing('title') // key is absent
req.isNotFilled('title') // absent or blank
req.hasAny(['a', 'title']) // any key present
req.anyFilled(['a', 'title']) // any key present and not blank

"Blank" means null, an empty string, an empty array or an empty object.

Run code conditionally on the presence of a key:

ts
req.whenHas('title', (value) => `has ${String(value)}`)
req.whenFilled('title', (value) => value, 'blank') // second argument is the fallback
req.whenMissing('page', () => 1)

Typed accessors ​

Input arrives as strings. These accessors coerce it, and return a default when the key is absent or cannot be read:

ts
req.boolean('published') // true for true, 1, '1', 'true', 'on', 'yes'; else false
req.boolean('published', true) // default when the key is absent
req.integer('page') // truncated toward zero, default 0
req.integer('page', 1)
req.float('price') // default 0
req.string('title') // String(value), default ''
req.enum('role', ['admin', 'user'] as const) // the value if it is one of them, else undefined
req.collect('tags') // a Collection from an array value

collect() with no key wraps all input values. See Collections.

Merging input ​

merge() and mergeIfMissing() return a new request, leaving the original untouched. They are useful in middleware for normalizing input:

ts
const normalized = req.merge({ slug: 'hello' })
normalized.input('slug') // => 'hello'
req.input('slug') // => undefined

req.mergeIfMissing({ role: 'user' }) // only adds keys that are absent

JSON ​

input() is enough for JSON objects. When the body is an array or scalar, or you want the raw decoded value, use json():

ts
req.isJson() // Content-Type contains /json
req.json() // the decoded body, or undefined when empty or invalid
req.json<{ title: string }>()
req.json([]) // a default for an empty or invalid body
req.body() // the raw body string

wantsJson() reports whether the client prefers JSON, which is true for an Accept header containing /json or +json, or for X-Requested-With: XMLHttpRequest. The exception handler uses it to choose between a JSON and an HTML error.

Headers ​

ts
req.header('accept') // => 'application/json'
req.header('x-none', 'fallback')
req.headers() // every header, lower-cased names
req.bearerToken() // the token from "Authorization: Bearer ..."

withHeader() returns a copy with a header set, for example to force a JSON response for a whole stack:

ts
const forced = req.withHeader('Accept', 'application/json')
forced.wantsJson() // => true

Cookies ​

ts
req.cookie('theme') // => 'dark', or undefined
req.cookies() // => { theme: 'dark', ... }

Values are URL-decoded. To set a cookie, see Responses.

Files and uploads ​

When the body is multipart/form-data, text fields appear in the normal input bag and file parts are available as UploadedFile objects. Files are held in memory.

ts
router.post('/avatar', (req) => {
  if (!req.hasFile('avatar')) return { error: 'no file' }

  const file = req.file('avatar') // UploadedFile, or an array if several parts share the name
  return {
    name: file.getClientOriginalName(), // 'me.PNG'
    ext: file.getClientOriginalExtension(), // 'png' (lower-cased)
    mime: file.getMimeType(), // 'image/png'
    size: file.getSize(), // bytes
  }
})

req.file(key) returns one UploadedFile when a single part used the name, an array when several did, and undefined when none did. Use req.files(key) to always get an array, and req.allFiles() for a map of every field to its file or files.

ts
for (const file of req.files('photos')) {
  file.storeAs('storage/photos', file.getClientOriginalName())
}

An UploadedFile can be read and persisted:

ts
file.get() // Buffer with the bytes (file.buffer() is an alias)
file.isValid() // true when the client sent a file name
file.store('storage/uploads') // writes under a generated unique name, returns the path
file.storeAs('storage/uploads', 'avatar.png') // returns 'storage/uploads/avatar.png'
file.move('/srv/exports/avatar.png') // an exact destination path
file.hashName() // a unique name that keeps the extension

Directories are created as needed. To store through a configured disk instead, read the bytes with file.get() and hand them to the Filesystem. To validate uploads, see Validation.

WARNING

The client chooses the file name and MIME type. Never trust them for security decisions, and generate your own storage names with store() or hashName().

Body size limit ​

When the node server adapter reads a request it buffers the body up to a limit of 1 MiB by default, and answers 413 Payload Too Large beyond it. Raise it with the maxBodyBytes option if you accept uploads: createServer(kernel, { maxBodyBytes: 10_000_000 }), or the fourth argument of serve(kernel, port, host, options).

Route parameters and bound models ​

ts
req.param('id') // a route parameter, string
req.param('page', '1') // with a default
req.params() // all route parameters
req.route<User>('user') // the bound model if a binding exists, else the string

See Routing.

Attributes ​

Middleware can attach request scoped values for later layers with withAttribute(), and read them with attribute(). Because requests are immutable, the new value is on the copy you pass to next:

ts
const tagged = req.withAttribute('user', { id: 1 })
tagged.attribute<{ id: number }>('user') // => { id: 1 }
req.attribute('user') // => undefined

The session middleware uses this to attach the session, see Session.

Released under the MIT License.