Status
Status code is an indicator of how the server handles the request.
You must have heard of the infamous 404 Not Found when you visit a non-existing page.
That's a status code.
By default, Elysia will return 200 OK for a successful request.
Elysia also returns many other status codes depending on the situation like:
- 400 Bad Request
- 422 Unprocessable Entity
- 500 Internal Server Error
You can also return a status code by returning your response using a status function.
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ status }) => status(418, "I'm a teapot'"))
.listen(3000)See Status.
Redirect
Similarly, you can also redirect the request to another URL by returning a redirect function.
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ redirect }) => redirect('https://elysiajs.com'))
.listen(3000)See Redirect.
Headers
Unlike status code and redirect, which you can return directly, you might need to set headers multiple times in your application.
That's why instead of returning a headers function, Elysia provides a set.headers object to set headers.
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ set }) => {
set.headers['x-powered-by'] = 'Elysia'
return 'Hello World'
})
.listen(3000)Because headers represents request headers, Elysia distinguishes between request headers and response headers by prefixing set.headers for response.
See Headers.
Assignment
Let's execrise what we have learned.
Show answer
- To set status code to
418 I'm a teapot, we can usestatusfunction. - To redirect
/docstohttps://elysiajs.com, we can useredirectfunction. - To set a custom header
x-powered-bytoElysia, we can useset.headersobject.
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ status, set }) => {
set.headers['x-powered-by'] = 'Elysia'
return status(418, 'Hello Elysia!')
})
.get('/docs', ({ redirect }) => redirect('https://elysiajs.com'))
.listen(3000)