I’ve been in the situation when I have a URL format like this web.com/p/[year]/[month] to show an posts archive, just like a typical WordPress slug.
It may looks simple, in next js you can build a page structure like this:
pages/
└── p/
└── year/
└── [month].jsIt’s quite clear and straightforward, but its also mean it would handle a request like this: web.com/p/2020/15 , and as we all know there’s only 12 month in a year, so than how could we handle this?
There’s 2 option that I could think of at the moment, I can just chill and shows user empty post in that page, or we can redirect user to another valid URL. In WordPress, it will remove the month path so you will redirected to web.com/p/2020 instead.
The problem is I would like to show the month name as a title, and I get the month name based on that slug, so if I get invalid month index from the slug that probably will breaks something
The Code
Basically, I want to write something like this
// [month].js
function BlogMonthlyArchive({ blogs }) {
// ...
}
export async function getServerSideProps({ query, res }) {
const month = parseInt(query.month);
const isValidMonth = month && month >= 1 && month <= 12;
if (!isValidMonth) {
// redirect ...
}
const blogs = await fetchData();
return {
props: { blogs },
};
}
export default BlogMonthlyArchive;notice that it has res object, quite familiar if you come from Node.js, and it means we can override the response object, but then in Next.js we should always return object inside getServerSideProps, otherwise it’s gonna be mad to you in the console, since we’re not gonna use it the component anyway, it’s okay to leave it as a empty object, so the redirect part became like this
// redirect ...
res.setHeader("location", `/p/${query.year}`);
res.statusCode = 302;
res.end();
return {};