Server middleware execution timing unclear in Nuxt 3
0 reputation · 30 May 2021, 11:51 UTC
0 reputation · 30 May 2021, 11:51 UTC
Goal: ensure that custom server‑side logic in Nuxt 3 server middleware runs before the page component renders so that date‑timezone conversion can be applied to incoming requests.
Uncertainty: it is not documented whether middleware defined under server/middleware is guaranteed to execute before the Nuxt rendering pipeline when exposeRoute is set to false, nor how its order relates to other nitro route handlers.
server/middleware is handled by Nitro at the very start of the request lifecycle, before any route handler or Vue component is instantiated.exposeRoute: false is used, does the middleware still run on every request? Yes. exposeRoute only controls whether the route is exposed as a standalone API endpoint; it does not affect the execution of Nitro middleware.console.log in the middleware and in a page‑side defineNuxtPlugin, or set a custom header in the middleware and read it with useRequestHeader inside the component. The log or header will appear before any rendering‑time code runs.Nuxt 3’s server layer is built on Nitro. The request pipeline is:
server/middleware (sorted alphabetically) are executed.exposeRoute: false) are matched.Because middleware runs at step 2, any modifications you make to event (headers, params, context) are available to the page component during its creation.
// server/middleware/timezone.js
export default defineEventHandler((event) => {
console.log('Middleware executed – converting timezone');
event.context.tz = 'America/New_York'; // example
});
// plugins/verifyOrder.client.ts
export default defineNuxtPlugin(() => {
console.log('Plugin executed – after middleware, before render');
});
// pages/index.vue
Run npm run dev and observe the console order: middleware → plugin → component. If you prefer to avoid console output, set a custom header in the middleware:
event.node.res.setHeader('x-tz', 'America/New_York');
Then read it in the component:
const tz = useRequestHeader('x-tz');
The value will be present before any client‑side rendering logic executes.
Nuxt 3 guarantees that server/middleware runs on every request, even when exposeRoute: false is set. Use the header‑or‑log trick to confirm the order without changing the UI.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.