Replies: 3 comments
-
| Hey @Vesafary! Unfortunately, you cannot use individual middlewares per  I'm interested in understanding the use case for why you need middleware per Router. Perhaps you are organizing your routes based on a specific logic, such as domain/entities/others, and you would like to apply the same Middleware to all routes in this case? | 
Beta Was this translation helpful? Give feedback.
-
| Hi @leandrodamascena! Thanks for your answer. There's a couple of reasons. The most important one to us: our application has a role-based authentication system (which is primarily handled by an API Gateway Authoriser), but a couple of endpoints have either role-based logic (e.g. an admin would fetch more (deleted) objects than a normal user) or instance-based logic (e.g. only the creator of an item is able to see it, or when the creator decides to share it). In these cases, a gateway authoriser can't do much more than accept the request, and the authentication has to be handled by the backend. This is what we're trying to do with a middleware, but to avoid someone forgetting to add it to a route (as per your example), or setting the wrong one, and to avoid code duplication and upon a refactor having to change dozens of endpoints, we want to add it globally as a "default" instead of on a per endpoint basis. However, that runs into the issue that some requests (e.g. OPTIONS, /swagger, some custom ones) have to be open-access. In my opinion, the nicest and easiest solution was to use multiple routers. BTW, as a follow-up it would also be nice if we could nest routers. Right now, you can only include a router on the app-level with a prefix, but not on another one. Usecase for this would be even further separation and less repetition between multiple domains. | 
Beta Was this translation helpful? Give feedback.
-
| I encountered a related challenge when refactoring a large Lambda handler by splitting routes into separate modules using the Router pattern. The ProblemWhen splitting routes into separate files, I needed to share middleware functions between the main app and router modules. However, this creates an import-time initialization problem: 
 Solution: Middleware Wrapper PatternSolved this with a wrapper function pattern that handles the initialization timing: # lambda_web_admin.py
from aws_lambda_powertools.event_handler.api_gateway import Router
# Placeholders for middlewares (set during initialization)
_force_authenticated = None
_setup_request = None
_user_request_permission = None
def init_admin_router(main_app, ..., force_auth, setup_req, user_perm):
    """Initialize the router with dependencies from main app."""
    global _force_authenticated, _setup_request, _user_request_permission
    _force_authenticated = force_auth
    _setup_request = setup_req
    _user_request_permission = user_perm
# Wrapper functions that exist at import time and delegate at runtime
def force_authenticated(app_param, next_middleware):
    """Wrapper for force_authenticated middleware."""
    return _force_authenticated(app_param, next_middleware)
def setup_request(app_param, next_middleware):
    """Wrapper for setup_request middleware."""
    return _setup_request(app_param, next_middleware)
def user_request_permission(app_param, next_middleware):
    """Wrapper for user_request_permission middleware."""
    return _user_request_permission(app_param, next_middleware)
# Create Router and use wrappers in route decorators
admin_router = Router()
@admin_router.route(
    "/admin",
    middlewares=[force_authenticated, setup_request, user_request_permission],
    method=["GET", "POST"],
    compress=True,
)
def admin():
    # Route handler
    passThen in the main file:   # lambda_web_function.py
  from lambda_web_admin import admin_router, init_admin_router
  # Initialize the router with actual middleware functions
  init_admin_router(
      main_app=app,
      force_auth=force_authenticated,
      setup_req=setup_request,
      user_perm=user_request_permission
  )
  # Register the router
  app.include_router(admin_router)Why This Works
 Suggestion for PowertoolsIt would be helpful if the documentation included a pattern for sharing middlewares across router modules, as this is a common need when refactoring monolithic handlers. A built-in way to "inject" middlewares into routers after import would also be cleaner than this workaround. | 
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Let's say I have multiple Routers to split routes, is it possible to give each router its own global middleware?
Right now, in my test setup, it seems like they are all piled together:
Beta Was this translation helpful? Give feedback.
All reactions