N
Nuxt•6mo ago
Phillip

appMiddleware in routeRules not working?

I want to run a middleware when my API in /server/api/admin/text-snippet.post.ts is being called but it doesn't run the middleware at all. Nuxt 3.12.2 nuxt.config.ts
routeRules: {
"/portal": { redirect: START_PAGE_AFTER_LOGIN },
'/portal/**': { ssr: false },
'/server/api/admin/**': { appMiddleware: 'mytest' }
},
routeRules: {
"/portal": { redirect: START_PAGE_AFTER_LOGIN },
'/portal/**': { ssr: false },
'/server/api/admin/**': { appMiddleware: 'mytest' }
},
middleware/mytest.ts
export default defineNuxtRouteMiddleware(async (to, _from) => {
console.log('getting in middleware') // <-- the issue: this is never being called
return false
})
export default defineNuxtRouteMiddleware(async (to, _from) => {
console.log('getting in middleware') // <-- the issue: this is never being called
return false
})
server/api/admin/text-snippet.post.ts
export default defineEventHandler(async (event) => {
console.log('getting in API') // <-- getting called
return { success: true }
})
export default defineEventHandler(async (event) => {
console.log('getting in API') // <-- getting called
return { success: true }
})
Then, I access the API via Postman. Method: Post. URL: http://localhost:3000/api/admin/text-snippet The response is { success: true } What am I missing or is this a bug?
2 Replies
Phillip
PhillipOP•6mo ago
Thank you so much! I moved it into server/middleware and now it's being executed 🙂 And then if the user is for example not authorized I'd do something like this?
if (userNotAuthenticated) {
throw createError({ status: 401 })
}
if (userNotAuthenticated) {
throw createError({ status: 401 })
}
Alright–but it does the job in my case. Thank you! I was looking 2 hours for a solution––thank you 😄
Cake
Cake•6mo ago
how do u do that? how do u make a wrapper for defineEventHandler and where would u define it? in server/utils?
Want results from more Discord servers?
Add your server