Skip to content

Instantly share code, notes, and snippets.

@orinokai
Last active November 3, 2022 11:46
Show Gist options
  • Save orinokai/39362a758ad841f2b09425bff4edfd83 to your computer and use it in GitHub Desktop.
Save orinokai/39362a758ad841f2b09425bff4edfd83 to your computer and use it in GitHub Desktop.
Next.js Advanced Middleware Transforms with Query Params and Prop Lookups
import { MiddlewareRequest } from "@netlify/next";
export async function middleware(nextRequest) {
const pathname = nextRequest.nextUrl.pathname;
const request = new MiddlewareRequest(nextRequest);
if (pathname.startsWith("/static")) {
const unit = nextRequest.nextUrl.searchParams.get("unit");
const response = await request.next();
// set pricing unit to query param value
response.transformData((data) => {
data.pageProps.unit = unit;
return data;
});
// fetch prices from data attribute and update page content
response.rewriteHTML("#price", {
element(element) {
const prices = JSON.parse(
decodeURIComponent(element.getAttribute("data-prices"))
);
element.setInnerContent(prices[unit].toString());
},
});
return response;
}
}
const Page = ({ prices, unit }) => {
return (
<div>
<h1 id="message">SSG page with middleware</h1>
<p>
Price:{" "}
<span
id="price"
data-prices={encodeURIComponent(JSON.stringify(prices))}
>
{prices[unit]}
</span>
</p>
</div>
);
};
export async function getStaticProps() {
return {
props: {
prices: {
yard: 3,
foot: 1,
},
unit: "yard",
},
};
}
export default Page;
@orinokai
Copy link
Author

orinokai commented Nov 3, 2022

This middleware will update the price accordingly with the query param ?unit=yard or ?unit=foot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment