HTTP Server
Built-in node:http server with zero configuration, trustProxy client-IP handling, raw request bodies for webhooks, and graceful shutdown.
On this page8
Overview
1import { Application } from '@axiljs/core'
2
3const app = new Application()
4
5app.get('/hello', (req, res) => {
6 res.json({ message: 'Hello from AxilJS' })
7})
8
9app.listen()Configuration
1const app = new Application({
2 server: {
3 port: 3000, // default 3000
4 host: '0.0.0.0', // default '0.0.0.0'
5 bodyLimit: '1mb', // default '1mb'
6 timeout: 30000, // ms to receive a whole request (Node requestTimeout); unset = Node default
7 headFallback: true, // HEAD falls back to the GET route (default true)
8 methodNotAllowed: false, // 405 + Allow header instead of 404 (default false)
9 trustProxy: false // default false (see below)
10 },
11 env: 'development', // default: NODE_ENV, else 'development'
12 prefix: '/api/v1', // global route prefix (default '')
13 prettyJson: true, // default true
14 logging: true // built-in request logger (default true)
15})Client IP and trustProxy
req.ip is the client address. By default it is the socket's remote address and the X-Forwarded-For header is ignored.
Warning
Changed in 0.3.3 (breaking): server.trustProxy now defaults to false. Earlier versions always trusted the left-most X-Forwarded-For entry, so any client could forge its IP, for example to escape per-IP rateLimit() limits by sending a different X-Forwarded-For value on every request. If your app runs behind a load balancer or reverse proxy, opt in explicitly; otherwise every client appears to have the proxy's IP and shares one rate-limit bucket.
| Value | req.ip is |
|---|---|
false (default) | The socket address. X-Forwarded-For is ignored. |
true | The left-most X-Forwarded-For entry. Only safe behind a proxy that overwrites the header; clients can forge it otherwise. |
a number n | The address n hops out from the socket, i.e. trust n proxies in front of the server. 1 means one proxy, so the last X-Forwarded-For entry is used. |
a function (address, hop) => boolean | Called from the socket address outwards; the first address it returns false for is the client. |
1// One reverse proxy (nginx, a cloud load balancer) in front of the app
2const app = new Application({ server: { trustProxy: 1 } })
3
4// Trust only proxies on the private network
5const internal = new Application({
6 server: {
7 trustProxy: (address) => address.startsWith('10.') || address === '127.0.0.1'
8 }
9})Request object
1app.post('/users/:id', (req, res) => {
2 req.method // 'POST'
3 req.path // '/users/42'
4 req.query // { page: '1' }
5 req.params // { id: '42' }
6 req.headers // request headers
7 req.body // parsed body (JSON, urlencoded, or text)
8 req.rawBody // unparsed body text, or undefined when there was no body
9 req.ip // client IP (see trustProxy)
10 req.locals // per-request data shared between middleware
11})Raw body for webhook signatures
Note
New in 0.3.3: the built-in body parser keeps the exact request text as req.rawBody and req.locals.rawBody (the latter for code typed against the axilRequest interface). It is set for every request that has a body; bodies of GET, HEAD and OPTIONS requests are not read.
Signature schemes such as GitHub's or Stripe's HMAC are computed over the bytes that were sent, not over re-serialized JSON, so verify against rawBody:
1import { createHmac, timingSafeEqual } from 'node:crypto'
2
3app.post('/webhooks/github', (req, res) => {
4 const secret = process.env.GITHUB_WEBHOOK_SECRET!
5 const expected = 'sha256=' + createHmac('sha256', secret)
6 .update(req.rawBody ?? '')
7 .digest('hex')
8 const received = String(req.headers['x-hub-signature-256'] ?? '')
9
10 const ok = received.length === expected.length &&
11 timingSafeEqual(Buffer.from(received), Buffer.from(expected))
12 if (!ok) return res.unauthorized('Invalid signature')
13
14 // req.body is still the parsed JSON payload
15 res.success({ received: true })
16})Response object
1res.json({ data: 'value' })
2res.status(201).json({ created: true })
3res.text('Hello')
4res.html('<h1>Hello</h1>')
5res.send(Buffer.from('raw bytes'))
6res.redirect('/other') // 302 by default
7res.header('X-Custom', 'value').json({ ok: true })
8
9// Envelope helpers: { status, code, message, data }
10res.success(users, 'Users fetched')
11res.created(user)
12res.paginated(items, total, page, limit)
13res.badRequest('Missing field')
14res.notFound('User not found')Listening and the startup banner
listen(port?, host?) resolves with the bound address, which is useful with port 0:
const { port, host } = await app.listen(0)The startup banner shows the installed @axiljs/core version (read from its package.json), the URL and the environment. It is printed only when logging is not false and env is not 'test', so test runs and apps created with logging: false stay quiet.
Graceful shutdown
await app.listen()
await app.close()Note
The server catches all unhandled errors and returns HTTP 500 without crashing. When NODE_ENV is production, 500 error messages are hidden from the client.
Throw NotFoundError, BadRequestError and the other HTTP error classes to choose the status, or add error middleware to shape the response. See Error Handling.
Was this page helpful?