What is @aws-sdk/middleware-stack?
@aws-sdk/middleware-stack is a package that provides a mechanism to compose middleware in the AWS SDK for JavaScript. It allows developers to add, remove, and modify middleware in the request/response lifecycle, enabling custom logic to be executed at various stages of the request processing.
What are @aws-sdk/middleware-stack's main functionalities?
Adding Middleware
This feature allows you to add custom middleware to the middleware stack. The middleware can perform actions before and after the request is processed.
const { MiddlewareStack } = require('@aws-sdk/middleware-stack');
const stack = new MiddlewareStack();
const myMiddleware = (next, context) => async (args) => {
console.log('Before request');
const result = await next(args);
console.log('After request');
return result;
};
stack.add(myMiddleware, {
step: 'initialize',
name: 'myMiddleware',
priority: 'high'
});
// Use the stack in a client
const client = new SomeAWSClient({ middlewareStack: stack });
Removing Middleware
This feature allows you to remove middleware from the middleware stack by specifying its name.
const { MiddlewareStack } = require('@aws-sdk/middleware-stack');
const stack = new MiddlewareStack();
const myMiddleware = (next, context) => async (args) => {
console.log('Before request');
const result = await next(args);
console.log('After request');
return result;
};
stack.add(myMiddleware, {
step: 'initialize',
name: 'myMiddleware',
priority: 'high'
});
// Remove the middleware
stack.remove('myMiddleware');
Modifying Middleware
This feature allows you to modify existing middleware in the middleware stack by adding a new middleware with the same name and step.
const { MiddlewareStack } = require('@aws-sdk/middleware-stack');
const stack = new MiddlewareStack();
const myMiddleware = (next, context) => async (args) => {
console.log('Before request');
const result = await next(args);
console.log('After request');
return result;
};
stack.add(myMiddleware, {
step: 'initialize',
name: 'myMiddleware',
priority: 'high'
});
// Modify the middleware
stack.add((next, context) => async (args) => {
console.log('Modified middleware');
return next(args);
}, {
step: 'initialize',
name: 'myMiddleware',
priority: 'high'
});
Other packages similar to @aws-sdk/middleware-stack
express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It allows for the use of middleware to handle requests and responses, similar to how @aws-sdk/middleware-stack allows for middleware in the AWS SDK.
koa
Koa is a new web framework designed by the team behind Express, aiming to be a smaller, more expressive, and more robust foundation for web applications and APIs. Koa uses async functions and provides a suite of methods for writing middleware, similar to @aws-sdk/middleware-stack.
hapi
Hapi is a rich framework for building applications and services. It enables developers to focus on writing reusable application logic instead of spending time building infrastructure. Hapi's plugin system is similar to the middleware stack in @aws-sdk/middleware-stack.
@aws-sdk/middleware-stack
The package contains an implementation of middleware stack interface. Middleware
stack is a structure storing middleware in specified order and resolve these
middleware into a single handler.
A middleware stack has five Step
s, each of them represents a specific request life cycle:
-
initialize: The input is being prepared. Examples of typical initialization tasks include injecting default options computing derived parameters.
-
serialize: The input is complete and ready to be serialized. Examples of typical serialization tasks include input validation and building an HTTP request from user input.
-
build: The input has been serialized into an HTTP request, but that request may require further modification. Any request alterations will be applied to all retries. Examples of typical build tasks include injecting HTTP headers that describe a stable aspect of the request, such as Content-Length
or a body checksum.
-
finalizeRequest: The request is being prepared to be sent over the wire. The request in this stage should already be semantically complete and should therefore only be altered to match the recipient's expectations. Examples of typical finalization tasks include request signing and injecting hop-by-hop headers.
-
deserialize: The response has arrived, the middleware here will deserialize the raw response object to structured response
Adding Middleware
There are two ways to add middleware to a middleware stack. They both add middleware to specified Step
but they provide fine-grained location control differently.
Absolute Location
You can add middleware to specified step with:
stack.add(middleware, {
step: "finalizeRequest",
});
This approach works for most cases. Sometimes you want your middleware to be executed in the front of the Step
, you can set the Priority
to high
. Set the Priority
to low
then this middleware will be executed at the end of Step
:
stack.add(middleware, {
step: "finalizeRequest",
priority: "high",
});
If multiple middleware is added to same step
with same priority
, the order of them is determined by the order of adding them.
Relative Location
In some cases, you might want to execute your middleware before some other known middleware, then you can use addRelativeTo()
:
stack.add(middleware, {
step: "finalizeRequest",
name: "myMiddleware",
});
stack.addRelativeTo(anotherMiddleware, {
relation: "before",
toMiddleware: "myMiddleware",
});
Removing Middleware
You can remove middleware by name one at a time:
stack.remove("Middleware1");
If you specify tags for middleware, you can remove multiple middleware at a time according to tag:
stack.add(middleware, {
step: "finalizeRequest",
tags: ["final"],
});
stack.removeByTag("final");