Creating a dynamic route with a parameter in NextJS that maps to a specific page

Currently, I'm developing a NextJS application and implementing Static HTML Export to make it a Jamstack app.

I'm facing an issue while setting up dynamic routes that depend on a username parameter included in the route: localhost:3000/:username/posts

For example: localhost:3000/jdoe/posts

This route should display all posts belonging to the user "jdoe."

My goal is to have the /posts page load statically without SSR and then fetch the posts using an API call. However, during build time, NextJS throws a 404 because it doesn't generate pages for specific usernames.

Is there a way to configure NextJS so that all requests to /:username/posts simply map to the posts page? I want to achieve this without SSR and without relying on query strings to specify the username, but rather have it as part of the path. I don't need a separate page generated for each username; all users should access the same page with their username used to load their respective posts.

Here's a glimpse of my directory structure:

directory structure

This method functions properly locally due to the presence of a development server. However, when deploying to my staging environment on Netlify using next export for Static HTML Export, the route breaks and returns a 404 error.

Currently utilizing Next version 10.0.5 and deploying to Netlify.

Thank you in advance!

Answer №1

It may not be feasible to utilize the next export feature for your specific scenario. If you absolutely require exporting it to static html, you might have to resort to using URL parameters. For instance, try something like /posts?username=john.

To retrieve these parameters in your page, you can utilize the useRouter hook. This method is compatible with the next export functionality.

import {useRouter} from 'next/router'

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

export default Posts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Develop an extensive Typescript and React shared library

Trying to develop a shared React and Typescript library has been quite challenging. Configuring the project workspace to work on both the library and application simultaneously has proven to be more difficult than anticipated. project ├─ app │ ├ ...

Error TS2339: Cannot access attribute 'reactive_support' on interface 'LocalizedStringsMethods'

Encountering the error TS2339: Property 'reactive_support' does not exist on type 'LocalizedStringsMethods' I recently updated TypeScript from version 2.6 to 2.9, and attempted import LocalizedStrings from 'react-localization&apo ...

Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style. This code snippet illustrates how the crawl is displaye ...

Is there a way to utilize variables in useEffect without including them in the dependency array?

Currently, I am dealing with an objectList and a size variable in my React component. const [objectList, setObjectList] = useState([]); // this array will be populated elsewhere const [size, setSize] = useState([props.width, props.height]); // the size may ...

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

Next.js fails to refresh the content upon initial view

Snippet from my index.js file: import Post from "@/components/Post" import Modal from "@/components/Modal" import {useState} from "react" export default function Home() { // Setting up states const [modalTitle, setModalTitle] = useState('Title&a ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

Utilize MaterialUI's stepper component to jazz up your design with

Is there a way to customize the color of a material ui Stepper? By default, the material UI stepper's icons use the primary color for both "active" and "completed" steps. class HorizontalLinearStepper extends React.Component { state = { activeS ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

Creating a seamless navigation experience using Material UI's react Button and react-router-dom Link

Is there a way to have the Material UI react Button component behave like a Link component from react-router-dom while preserving its original style? Essentially, how can I change the route on click? import Button from '@material-ui/core/Button' ...

The countdown feature is failing to update despite using the SetInterval function

My goal is to develop a countdown application using Atlassian Forge that takes a date input and initiates the countdown based on the current date. For instance, if I input "After 3 days from now," I am expecting the result to continuously update every seco ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

"Encountering a 'react-scripts start' error while setting up on a different device

After creating a project on MacOS using "create react app" and committing it to Git, I am now facing an issue when cloning the folder on Windows. I have followed the usual steps: node npm npm install However, I encountered the following error: $ npm ...

Transforming the DevExtreme Dialog/Popup component into a MaterialUI equivalent in React using JavaScript

After deciding to move away from using DevExtreme/DevExpress components, I am now facing the challenge of transitioning my Popup / Dialog component. The previous popup system worked by rendering in the background and then displaying when a specific visibl ...

Guide on embedding a form component within an iframe using ReactJS

I am trying to figure out how to render my form component inside an iframe, but so far it's only rendering the iframe itself. Any tips on how to accomplish this task? import './App.css'; import ReactDOM from "react-dom/client" impo ...

What are some tips for creating an improved React list container component?

I have a small application that fetches movie data. The component hierarchy is not very complex. The state is stored in App.js and then passed down to the Movies.js component, which simply displays a list of movies in a ul element. Data passing from App.j ...

Display a loading splash screen prior to loading Next.js

I am working on a NextJS website and I'm looking to incorporate a Splash Screen that displays before the site is fully loaded. However, since the Splash Screen is included in the NextJS code, it ends up loading after NextJS has rendered on the server ...

Styles are absent from the NextJS 13.4 App Router Middleware Page Redirect feature

Currently, I have implemented middleware that redirects users if they are not on the sign-in screen. This is only a test scenario, and in the future, it will check for a valid authentication session before redirecting. However, after the redirect, the pag ...

After fetching, null is returned; however, refreshing the page results in the object being returned. What is the

I have a specific case where I am dealing with an array of 500 post IDs and I need to retrieve the first 100 posts. To achieve this, I implemented the following code: API https://github.com/HackerNews/API BASE_URL = 'https://hacker-news.firebaseio.com ...