You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I can log server event timings as middleware like this:
exportdefaultdefineEventHandler((event)=>{const{ req, res }=event.nodeconststartTime=Date.now()logger.info(`event start: ${req.url}`)res.on('finish',()=>{constendTime=Date.now()logger.info(`Request finished: ${endTime-startTime}ms`)})})
Middleware is run on every request, there's no way to add middleware to specific routes like with express.
Instead, you can check the request URL and run it then.
exportdefaultdefineEventHandler((event)=>{// Will only execute for /auth routeif(getRequestURL(event).startsWith('/auth')){event.context.user={name: 'Nitro'}}})
middleware is executed in top-down order, order by priority with perfixes 1.first.ts | 2.second.ts do the same for folders 1.firstDir | 2.secondDir
middleware can modify the request before it is processed, not after.
returning anything from a middleware will close the request.
example of use restricting admin api routes:
exportdefaultdefineEventHandler((event)=>{logger.info('run auth check before other middleware')const{ res }=event.nodeconstisAdmin=falseif(event.path.startsWith('/api/admin')){if(!isAdmin){logger.info('not an admin')// res.end('status: 403, message: You are not an admin')return{status: 403,body: 'You are not an admin'}}logger.info('you are an admin, continue with other middleware')}})
you can use either return { } or res.end() to terminate the request. return is preferable imo because it returns structured JSON to the screen.
sendRedirect(event, redirectPath, 302) can also be used instead of returning any data. Although for redirects I think it makes sense to do that on the client side.
This is a running thread of my findings about nitro middlewares.
The text was updated successfully, but these errors were encountered: