N
Nuxt2y ago
Alireza

Is it possible to select/define which server middlewares should be run on a specific server route?

For example I have a collection of routes under /server/api/user and I need all of them to run /server/middleware/auth.ts . How do you go about it?
3 Replies
Alireza
AlirezaOP2y ago
Would something like this work?
export default defineEventHandler( async (event) => {

const url = getRequestURL(event);

if (url.pathname.startsWith("/api/user") ){

const user = getUser()
if (!user) {
throw createError({
statusCode: 401,
statusMessage: "unauthorized",
});
}
}
})
export default defineEventHandler( async (event) => {

const url = getRequestURL(event);

if (url.pathname.startsWith("/api/user") ){

const user = getUser()
if (!user) {
throw createError({
statusCode: 401,
statusMessage: "unauthorized",
});
}
}
})
Cake
Cake2y ago
@Alireza check this example out https://github.com/insidewebdev/twitter-clone/blob/master/server/middleware/auth.js
const endpoints = [
'/api/auth/user',
'/api/user/tweets',
'/api/tweets',
'/api/tweets/:id'
]

const isHandledByThisMiddleware = endpoints.some(endopoint => {
const pattern = new UrlPattern(endopoint)

return pattern.match(event.req.url)
})

if (!isHandledByThisMiddleware) {
return
}
const endpoints = [
'/api/auth/user',
'/api/user/tweets',
'/api/tweets',
'/api/tweets/:id'
]

const isHandledByThisMiddleware = endpoints.some(endopoint => {
const pattern = new UrlPattern(endopoint)

return pattern.match(event.req.url)
})

if (!isHandledByThisMiddleware) {
return
}
Alireza
AlirezaOP2y ago
Thanks @Cake
Want results from more Discord servers?
Add your server