@@ -69,8 +69,16 @@ import { decodeAndVerifyJwtToken } from '~/somewhere/in/utils'
69
69
export async function addTodo(todo : Todo ) {
70
70
const event = useEvent ()
71
71
72
- const authorization = getRequestHeader (event , ' authorization' )
73
- const user = await decodeAndVerifyJwtToken (authorization .split (' ' )[1 ])
72
+ async function getUserFromHeader() {
73
+ const authorization = getRequestHeader (event , ' authorization' )
74
+ if (authorization ) {
75
+ const user = await decodeAndVerifyJwtToken (authorization .split (' ' )[1 ])
76
+ return user
77
+ }
78
+ return null
79
+ }
80
+
81
+ const user = await getUserFromHeader ()
74
82
75
83
if (! user ) {
76
84
throw createError ({ statusCode: 401 })
@@ -89,6 +97,37 @@ export async function addTodo(todo: Todo) {
89
97
90
98
You can use all built-in [ h3 utilities] ( https://github.com/unjs/h3#built-in ) inside your exported functions.
91
99
100
+ ## createContext
101
+
102
+ Each ` .server. ` file can also export a ` createContext ` function that is called for each incoming request:
103
+
104
+ ``` ts
105
+ export function createContext() {
106
+ const event = useEvent ()
107
+
108
+ async function getUserFromHeader() {
109
+ const authorization = getRequestHeader (event , ' authorization' )
110
+ if (authorization ) {
111
+ const user = await decodeAndVerifyJwtToken (authorization .split (' ' )[1 ])
112
+ return user
113
+ }
114
+ return null
115
+ }
116
+
117
+ event .context .user = await getUserFromHeader ()
118
+ }
119
+
120
+ export async function addTodo(todo : Todo ) {
121
+ const event = useEvent ()
122
+
123
+ if (! event .context .user ) {
124
+ throw createError ({ statusCode: 401 })
125
+ }
126
+
127
+ // addTodo logic
128
+ }
129
+ ```
130
+
92
131
## useAsyncData
93
132
94
133
` nuxt-remote-fn ` can work seamlessly with [ ` useAsyncData ` ] ( https://nuxt.com/docs/api/composables/use-async-data/ ) :
0 commit comments