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.

typescript
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.

typescript
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.

typescript
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.

  1. Return a 418 Status

    Let's create a GET `/` endpoint that returns 418 status

  2. Create a Redirect

    Redirect a GET `/docs` endpoint to `https://elysiajs.com`

  3. Add Powered By Header

    In GET `/` endpoint, return a custom header `x-powered-by` set to `Elysia`

Show answer
  1. To set status code to 418 I'm a teapot, we can use status function.
  2. To redirect /docs to https://elysiajs.com, we can use redirect function.
  3. To set a custom header x-powered-by to Elysia, we can use set.headers object.
typescript
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)
  • index.ts