Last active
November 3, 2022 11:46
-
-
Save orinokai/39362a758ad841f2b09425bff4edfd83 to your computer and use it in GitHub Desktop.
Next.js Advanced Middleware Transforms with Query Params and Prop Lookups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This middleware will update the price accordingly with the query param
?unit=yard
or?unit=foot