NuxtN
Nuxt2y ago
Pipriles

Server middlewares issue

Hello everybody, I have a doubt regarding how server middlewares should work. I have a middleware located in server/middleware/auth.ts that throws an error when the users that sends the request is not authenticated... But it turns out that when I load any page that server middleware gets called. I thought those middlewares were only called on the api/server layer and didn't affect the nuxt pages initial load?

export default defineEventHandler((event) => {

  const url = getRequestURL(event);

  if (
    url.pathname.startsWith('/api/connect') ||
    url.pathname.startsWith('/connect') ||
    url.pathname.startsWith('/api/auth')
  ) return console.log('[Skipping Auth]');

  if (!isAuthenticated(event)) {
    const message = `Access not allowed to ${url.pathname}`;
    throw createError({ statusCode: 401, statusMessage: 'Unauthorized', message });
  }

});
Was this page helpful?