Karthik
Karthik

Reputation: 31

Next js dynamic routes work as expected in development but returns 404 page in production

I am trying to use dynamic routes to render pages using next js. When user hits the url (http://localhost:3000/post/123) it should render a page and I should be able to pull the id from the url using useRouter() hook and display it in the page as shown below. This works perfectly fine in local dev but when I host this on firebase, the url returns 404 page. I am confused what's wrong. Please help.

// [post].tsx
import React from 'react'
import { useRouter } from 'next/router'

const Details = () => {
    
    const { query } = useRouter()
    const postID = query.post

    return (
        <div>Post id: {postID}</div>
    )
}

export default Details

package.json: package.json:

Folder structure: Folder structure:

Upvotes: 2

Views: 1336

Answers (1)

Shankaja Aroshana
Shankaja Aroshana

Reputation: 579

For the URL http://localhost:3000/post/123 the router.query object would look like this

//[post].jsx/tsx
{ "post": "123" }

What you name inside the [ ] in your case, post would be the variable name returned by the router

It takes some time to hydrate so I would recommend you to use useEffect to capture the id.

const router = useRouter()
const {post} = router.query

useEffect(()=>{
  if(!post) return
  //get from firebase
},[router])

NEXT JS Dynamic Routing Documentation

Upvotes: 1

Related Questions