Mike Ng
Mike Ng

Reputation: 11

Making NextJS map dynamic route with param to page

I am writing a NextJS app and using the Static HTML Export as I want my app to be Jamstack app.

I am trying to set up my routes with dynamic routes that they are based on a username param that is part of the route: localhost:3000/:username/posts

Example: localhost:3000/jdoe/posts

This route will show all the posts for the user jdoe.

I want my /posts page to load staticly without SSR and then fetch the posts via an API call.

However, NextJS throws a 404 because at build time it does not generate the page for the specific username.

Is there a way to tell NextJS that all requests to /:username/posts should just map to the posts page? I would like to do this without SSR and without having to use querystring to specify the username but have it as part of the path. I don't need a page to be generated for every username. Just want all my users to load the same page and have the username param in the route to use for loading their posts.

My directory structure looks like this:

directory structure

This approach works locally because there is a dev server. However when I deploy to my staging env in Netlify, I use next export for the Static HTML export and that's where the route breaks and returns a 404.

I am using Next 10.0.5 and deploying to Netlify

Thanks in advance!

Upvotes: 1

Views: 748

Answers (1)

ultrayam
ultrayam

Reputation: 144

Unfortunately it might not be possible to use next export for your use case. If you really need to export it to static html then you might need to use URL parameters. For example, /posts?username=john.

In your page, you can get the parameters with useRouter. This will work with next export.

import {useRouter} from 'next/router'

function Posts() {
  const router = useRouter();
  return <h1>{router.query.username}</h1>
}

export default Posts

Upvotes: 0

Related Questions