⚙ Generate routes dynamically +v0.7
What if you want to generate pages dynamically based off some data from an API? Let's say you want to generate blog posts with a unique URL, you can now that!
Basic setup
Create a file called hydrogen.routes.js
in the root of your project
module.exports = async () => [
{
path: '/blogs/setting-up-hydrogen',
data: {
post: 1,
},
},
{
path: '/blogs/setting-up-a-service-worker',
data: {
post: 2,
},
},
];
The above function will return an array of routes that can be dynamically generated. We can think of the path like this /blogs/:dynamic-route
so if you we run npx hydrogen build
it will generate pages like this:
/dist
|_ /blogs
|_ /setting-up-hydrogen
|_ index.html
|_ /setting-up-a-service-worker
|_ index.html
Hydrogen will also inject the route information into the Head API, Data API and the Page Template.
Setting up a dynamic page template
All dynamic page templates are prefixed with an underscore, so a dynamic page will always look this _index.js
const page = ({ data }) => `
<p>${data.content}</p>
`;
module.exports = {
layout: 'default',
title: 'Hydrogen webpage',
page,
data: async ({ route }) => ({
content: await axios.get('https://api.blog.com/post=${route.data.post}'),
}),
};