@@ -15,13 +15,16 @@ head:
15
15
---
16
16
17
17
# After Handle
18
+
18
19
Execute after the main handler, for mapping a returned value of ** before handle** and ** route handler** into a proper response.
19
20
20
21
It's recommended to use After Handle in the following situations:
21
- - Transform requests into a new value, eg. Compression, Event Stream
22
- - Add custom headers based on the response value, eg. ** Content-Type**
22
+
23
+ - Transform requests into a new value, eg. Compression, Event Stream
24
+ - Add custom headers based on the response value, eg. ** Content-Type**
23
25
24
26
## Example
27
+
25
28
Below is an example of using the after handle to add HTML content type to response headers.
26
29
27
30
``` typescript
@@ -32,7 +35,7 @@ new Elysia()
32
35
.get (' /' , () => ' <h1>Hello World</h1>' , {
33
36
afterHandle({ response , set }) {
34
37
if (isHtml (response ))
35
- set .headers [' Content-Type ' ] = ' text/html; charset=utf8'
38
+ set .headers [' content-type ' ] = ' text/html; charset=utf8'
36
39
}
37
40
})
38
41
.get (' /hi' , () => ' <h1>Hello World</h1>' )
@@ -47,28 +50,34 @@ The response should be listed as follows:
47
50
| /hi | text/plain; charset=utf8 |
48
51
49
52
## Returned Value
53
+
50
54
If a value is returned After Handle will use a return value as a new response value unless the value is ** undefined**
51
55
52
56
The above example could be rewritten as the following:
57
+
53
58
``` typescript
54
59
import { Elysia } from ' elysia'
55
60
import { isHtml } from ' @elysiajs/html'
56
61
57
62
new Elysia ()
58
63
.get (' /' , () => ' <h1>Hello World</h1>' , {
59
64
afterHandle({ response , set }) {
60
- if (isHtml (response ))
65
+ if (isHtml (response )) {
61
66
set .headers [' content-type' ] = ' text/html; charset=utf8'
67
+ return new Response (response )
68
+ }
62
69
}
63
70
})
64
71
.get (' /hi' , () => ' <h1>Hello World</h1>' )
65
72
.listen (3000 )
66
73
```
67
74
68
- Unlike ** beforeHandle** , after a value is returned from ** afterHandle** , the iteration of afterHandle ** will __ NOT __ be skipped.**
75
+ Unlike ** beforeHandle** , after a value is returned from ** afterHandle** , the iteration of afterHandle ** will ** NOT ** be skipped.**
69
76
70
77
## Context
78
+
71
79
` onAfterHandle ` Context is extends from ` Context ` with additional properties of the following:
72
- - response: Response to return to the client
80
+
81
+ - response: Response to return to the client
73
82
74
83
All of the context is based on normal context and can be used like normal context in route handler.
0 commit comments