-
Notifications
You must be signed in to change notification settings - Fork 0
Middleware
In general terms a "middleware" is that logic executed as a pipe which acts whenever a Request is received and also when a Response is given. In other words, it pre-processes a Request before being processed and also post-processes a response.
In Astro the middleware must be declared as a Module called middleware and must be located in the src folder.
This condition is satisfied by one of both:
- by having a
src/middleware.[js|ts]file - by having a
src/middleware/index.[js|ts]file
Astro allows middleware adding behaviours on Requests interception and also on Responses interception.
First ones are accomplished by placing that behaviour logic before calling the next() function, and following ones after that call.
Furthermore, those logics can be divided into pieces, which consists in a sequence of MiddlewareHandlers where the request and produced response will be "piped-through".
In our case the middleware resides in the folder middleware/, and is exported with the file middleware/index.ts
If you take a look at the code of this file, you will see a sequence piping three middlewares called routes, auth, and response.
flowchart TB;
evt(( ))
stp((( )))
subgraph REQUEST PROCESSING
direction LR
subgraph Astro Server
direction TB
Request(Request received)
Response[/Response/]
end
evt-->Request
subgraph Middleware
direction TB
Routes{{RoutesMiddleware}}
Auth[AuthorizationMiddleware]
Slzr{{ResponseMiddleware}}
end
Request-- event interception ---Routes
Routes-->Auth
subgraph Pages/Endpoints
Processing[[Request processing]]
end
end
Response-->stp
Slzr-->Response
Processing-->Slzr
Auth-->Processing & Slzr
During the interception of request, first middleware (provided by the
routes file loads the routes configured in the private routes.json file into the context.locals.This load makes those routes being available for the rest of middlewares and pages.
Once private routes are available in the property
routes at the context.locals global object, the requested route is matched against those private routes.If user is not logged in, this middleware (provided by the [`routes` file](Middleware-(Code)#auth)) responds directly with a redirection.
This middleware helps in the serialization of the Response content to the appropiate format infered from the Request
Accept header.There are some endpoints that are called via
fetch and its Accept header reports the expectation of a Response agree with it, usually application/json.