[SOLVED] How to generate api and pages for all days in a year – React/Next JS?


This Content is from Stack Overflow. Question asked by Kal

I have an api that can accept all days of a year and return information for all days.


Right now, I have a page called https://mywebsite.org/today which returns info for today.
My goal is to make the page available for all days of the year. For example Feb 28 would be:


will pass 02 (month) and 28(day) to the api.

My routes are very simple. For Example for users, my route looks like below but users are stored in a database. I am not guessing or making up values like I want to do for dates.


I can create a route called /today/[date]/index.js but how to create this for all days of the year?

I would like users to be able to just enter any month/day.


What you need to use is called Dynamic Routes (you can read more about here)

First of all you need to name the file like this pages/[...params].js
That will match a set of routes like:

 1. /feb
 2. /feb/23
 3. /a/b/c

Don’t forget to validate the parameters (I suppose third case should redirect to 404)

You can use useRouter hook to get the parameters from the URL:

import { useRouter } from 'next/router'

const Component = () => {
  const router = useRouter()
  const { params} = router.query // this will return an array of query parameters

  // parameters validation here

  return <></>

export default Component 

This Question was asked in StackOverflow by Kal and Answered by Victor It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?