Outsmartly
Search…
Middleware
Middleware is used to alter the behavior of a request both before and after Outsmartly makes the request to your origin server and applies any overrides, if applicable.
The signature of a middleware is a function which accepts two arguments: an OutsmartlyMiddlewareEvent and a next() function. The OutsmartlyMiddlewareEvent contains additional information such as the OutsmartlyRequest object, OutsmartlyEdgeVisitor, helpers for cookies, and more.
Middleware should call next() whenever they want to continue on to the "next" middleware, or if it's the last middleware, continue to the default, built-in functionality of Outsmartly.
1
// a function which accepts an event object and a next() function.
2
type Middleware = (
3
event: OutsmartlyMiddlewareEvent,
4
next: (request?: Request) => Promise<Response>,
5
) => PromiseOrValue<Response>;
6
7
type PromiseOrValue<T> = Promise<T> | T;
Copied!
It's a good practice to give your middleware functions names so that if there are any errors inside them, the error message seen in the browser response will contain the name of the middleware, to aid in debugging.
This pattern gives you the most flexibility: you can do things before, and after the default behavior. Not only that, you can also pass a different Request object when you call next(request) which then changes what request will actually be made.
The simplest middleware that does nothing (no-op) looks like this:
1
function exampleMiddleware(event, next) {
2
return next();
3
}
Copied!
Middleware can be provided in you outsmartly.config.js in two places: at the top-level (applying all routes) or alternatively in a route itself (applying only paths that match.)
1
export default {
2
host: 'example.outsmartly.app',
3
environments: [
4
{
5
name: 'production',
6
origin: 'https://my-example-website.vercel.app',
7
},
8
],
9
// All routes will have this middleware applied
10
middleware: [
11
function firstMiddleware(event, next) {
12
return next();
13
},
14
],
15
routes: [
16
{
17
// Any paths that start with /some-base-path/ will have
18
// this middleware applied.
19
path: '/some-base-path/*',
20
middleware: [
21
function secondMiddleware(event, next) {
22
return next();
23
},
24
],
25
},
26
],
27
};
Copied!
But that's not a very exciting piece of middleware. So let's see how we might add headers both to the request AND the response:
1
async function authorizationRedirectMiddleware(event, next) {
2
// The request objects are not directly mutable, so we have to create our
3
// own copy, using the existing headers and request as a base.
4
const headers = new Headers(event.request.headers);
5
headers.set('My-Custom-Request-Header', 'something');
6
const request = new Request(event.request, {
7
headers,
8
});
9
10
// Move on to the next middleware, or built-in behavior. When this promise
11
// resolves, we have already received the initial response from the origin
12
// server (or the cache.)
13
const response = await next(request);
14
response.headers.set('A-Different-Response-Header', 'another-thing');
15
16
// If you wanted to, you could even return a totally different response.
17
return response;
18
}
Copied!
You don't HAVE to call next(), but if you don't, remember that then Outsmartly will not make any requests to your origin or apply overrides to any HTML.

Examples

Sometimes you want to set a cookie from the edge/server so that it can be an httpOnly cookie, which makes it inaccessible from client-side JavaScript in the browser (better security) and also is much more likely to survive longer without the browser or extensions deleting it.
Often this is inside an interceptor, but if you need to do this from middleware, it is also possible. Here's an example where we set a cookie the first time you land on a product page, so we can later tell to do things like personalization/recommendations.
1
export default {
2
host: 'example.outsmartly.app',
3
environments: [
4
{
5
name: 'production',
6
origin: 'https://my-example-website.vercel.app',
7
},
8
],
9
routes: [
10
{
11
path: '/products/:productName',
12
middleware: [
13
async function landPageProductNameMiddleware(event, next) {
14
if (!event.cookies.has('myapp-landingPageProductName')) {
15
// Get the product name so we can track which
16
const { productName } = event.request.outsmartly.params;
17
event.cookies.set('myapp-landingPageProductName', productName, {
18
httpOnly: true,
19
path: '/',
20
// Expires in a year
21
maxAge: 60 * 60 * 24 * 7 * 52,
22
});
23
}
24
25
// Otherwise, defer to the default behavior.
26
// It's important to call this if you don't need to redirect!
27
return await next();
28
},
29
],
30
},
31
],
32
};
Copied!

Redirects

In this example, for request paths that start with /app/ we check if they are authorized, and if not, we redirect them to the /login page.
This demonstrates the using the request's path from event.url.pathname, along with getting a cookie named 'session' by using the event.cookies utility.
1
function isAuthorized(sessionCookieValue) {
2
// Somehow decide whether or not they are authorized.
3
// e.g. using JSON Web Tokens
4
return false;
5
}
6
7
export default {
8
host: 'example.outsmartly.app',
9
environments: [
10
{
11
name: 'production',
12
origin: 'https://my-example-website.vercel.app',
13
},
14
],
15
routes: [
16
{
17
path: '/app/*',
18
middleware: [
19
async function authorizationRedirectMiddleware(event, next) {
20
// Redirects work by providing a status and a Location header
21
// to where you want to redirect the browser. No body is needed,
22
// which is why we pass null.
23
if (!isAuthorized(event.cookies.get('myapp-session'))) {
24
return new Response(null, {
25
status: 302,
26
headers: {
27
Location: '/login',
28
},
29
});
30
}
31
32
// Otherwise, defer to the default behavior.
33
// It's important to call this if you don't need to redirect!
34
return await next();
35
},
36
],
37
},
38
],
39
};
Copied!
Last modified 2mo ago