profile
viewpoint

Ask questionsRequest: Add middleware property to context

Hi! When using middlewares, it would be beneficial to pass along information, e.g. when authenticating.

Example, a JWT middleware:

const jwtMiddleware: RouterMiddleware = async (ctx, next) => {
	await next();
	let isUnauthorized = true
	let isExpired = false

	if (ctx.request.headers.has("Authorization")) {
		const authHeader = ctx.request.headers.get("Authorization")!
		if (authHeader.startsWith("Bearer ") && authHeader.length > 7) {
			const token = authHeader.slice(7)
			const decryptedToken = await validateJwt(token, SECRET_KEY, { isThrowing: false })
			if (decryptedToken && decryptedToken.payload?.iss) {
				isUnauthorized = false
				ctx.params.CTX_USER = decryptedToken.payload.iss
			}
		}
	}

	if (isUnauthorized) {
		ctx.throw(ErrorStatus.Unauthorized, isExpired ? "Token expired" : "Authentication failed")
	}
}

As you can see, I use ctx.params.CTX_USER to pass the information to the rest of the application, but it would be better if there would be a ctx.middleware or something similar available to pass the information along.

I really enjoy this module, thanks for your hard work!

oakserver/oak

Answer questions kitsonk

This is what ctx.state is for... It can be strongly typed as well, by using the generic. Is there something missing from that?

useful!

Related questions

No questions were found.
Github User Rank List