Execute middleware before resolving route


#1

I am attempting to register a middleware that would add support for specifying the request localization through the URL by parsing the URL and then setting the URL of the request with the locale portion stripped.

However, I am having some issue as once I make a request with the locale in the URL, the framework throws a 404 as it appears that the framework is attempting to resolve the route before executing the global middleware.

My assumption would have been that the framework would execute any global middleware first, before trying to lookup the route.

Is it possible to have my middleware executed before the route is looked up? This would allow me to manipulate the request object before the framework handles it.

app/middleware/LocaleMiddleware.js

const resolver = use('Locale/Resolver');

class LocaleMiddleware {

  async handle ({ request }, next) {
    const result = resolver.resolve({
      host: request.hostname(),
      url: request.url(),
      headers: request.headers()
    });
    request.request.url = result.url;
    await next();
  }
}

start/kernel.js

const globalMiddleware = [
  'Adonis/Middleware/BodyParser',
  'Adonis/Middleware/Session',
  'Adonis/Middleware/Shield',
  'Adonis/Middleware/AuthInit',

  // application middleware
  'App/Middleware/LocaleMiddleware',
]

#2

Yes add it to the server middleware stack. Cors is an example of same

More here http://adonisjs.com/docs/4.1/http-context#_request_flow


#3

Woops! I should have RTFM.

Thanks for the reply and help!