Add header to request #4287
-
Hello, I want to know if it is possible to add a header to all request received through midleware. That is, I want to make a global middleware that adds an additional header before going to route. I hope you understand my problem. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi ! |
Beta Was this translation helpful? Give feedback.
-
Yep, you can reach through to the underlying request object and set it directly. Here's an example piggybacking off the export default class SilentAuthMiddleware {
/**
* Handle request
*/
public async handle({ auth, request }: HttpContextContract, next: () => Promise<void>) {
/**
* Check if user is logged-in or not. If yes, then `ctx.auth.user` will be
* set to the instance of the currently logged in user.
*/
// try to get token from cookies, if found, set authorization
const token = request.cookie('auth-session')
if (token) {
request.request.headers['authorization'] = `Bearer ${token}`
}
await auth.check()
await next()
}
} Also note that if you're able to use cookies, then just using session auth instead of token-based auth would be an easier solution. |
Beta Was this translation helpful? Give feedback.
Yep, you can reach through to the underlying request object and set it directly. Here's an example piggybacking off the
SilentAuth
middleware.