NextJS route gives 404 when not using Link - next.js

I have a Next.js page, where the pages are statically generated (using next export). It's a dynamic route, but I will only fetch data on the client after the initial page load (in a useEffect).
The path is something like: /pages/foo/[id].tsx. This is in fact the only route which is going to exist.
My problem is:
If I access the URL directly (e.g. typing in https://mysite.fake/foo/1337 into the URL bar) I get a 404.
If I navigate to that route using a <Link /> it does work as expected
If I then reload the page, I get a 404 again.
On local dev, it works fine. The problem only exists when deployed.
The page in question is using the router.query, but I have the same problem with a completely static page (e.g. just /pages/bar/baz.tsx).
Example:
export const Home: NextPage = () => {
const router = useRouter()
const { id } = router.query
const headerText = id ? `Hello ${id.toString()}` : ''
// in a later iteration, I will use the query id to fetch data in a useEffect
return <h1>{headerText}</h1>
}
As far as I understand from the Next.js documentation on dynamic routing and data fetching this should be possible to do.
My next.config.js is very bare:
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
}
What am I doing wrong?

Related

nextjs links without strings

Im new to nextjs, and Im checking if it will be good for the app that will have pretty complex and messy internal navigation. Just checked their documentation and I see that they recommend usage
of Link component like this <Link href="/your_path">Path</Link>. A bit scary is that I have to provide 'your_path' as a string so every time i change page file name I have to manually update code that redirects to this page. Is there any solution that allows me to define routing on my own so I can write something like (pseudocode)
routes = [
...
{
page : 'page_name',
path : 'path_to_page'
}
...
]
So instead of using string I can do <Link href="{route.path}">Path</Link> or Im condemned to use this file-system based router with all consequences?
The simple answer is yes!
When you want to change a user route in NextJs you have 2 options,
The first is with the <Link> Element that you can specify a href to where it directs.
And you also have a useRouter hook for more complex routing for example if the user does an action that requires moving him into a different route you can do it internally in your handlers.
For more information about useRouter hook.
What I usually do is storing my routes in an object
const ROUTES = {
HOME: "/",
ABOUT: "/about"
}
and wherever you call routes you just use the object so F.E
With Link tag
<Link href={ROUTES.ABOUT}>ABOUT PAGE</Link>`
with useRouter hook
// Inside a React Component
const router = useRouter();
const handleNavigateToAbout = () => {
router.push(ROUTES.ABOUT);
}
return (
// SOME JSX
<button onClick={handleNavigateToAbout}> Go to about page! </button>
)

Nextjs nested routing not found

I'm trying to create a nested route inside my nextjs project, but i'm receiving a 404 page not found when trying to request the page.
I have a route named /dashboard/repository/blender where blender is a dynamic name that the user can input and that works fine.
But the next step is then to create a subpage for that dynamic route which is named tags, and that's where I receive the 404. (/dashboard/repository/blender/tags)
Here's a screenshot of what i've tried to achieve the tags nested routing
Secondly I have also tried doing the following
What can I do to achieve this ?
Try that structure please
dashboard (folder)
-repository (folder)
--[blender] (folder)
----tags.tsx (file)
example urls
/dashboard/repository/blender/tags
/dashboard/repository/surrender/tags
...
In your component, you can get it like below
tags.tsx
import { useRouter } from 'next/router'
const C = () => {
const router = useRouter()
const { blender } = router.query;
console.log(blender)
}
Solved it with
- /dashboard/repository/[repository]/index.js
- /dashboard/repository/[repository]/tags.js

Getting a query param off of a dynamic page in next.js, possible?

I am finding IF a user enters my next.js site directly WITH query params on it. Mind you, the page itself is dynamic so it has internal "param". Using useRouter is NOT "seeing" the additional actual query param.....
So, I enter my site like so: Hard reload
-=> http://localhost/sku/1234?discount_id=TESTER
useRouter => query, only shows "1234" as being query{id: '1234'}. Nowhere IN the object of router is discount_id or its value?
This seems like a bug, no? I have to parse that myself?
The router.query param includes both dynamic route params and query params.
Try this code:
// File location: /pages/sku/[sku].tsx
import { useRouter } from "next/router";
const Page = () => {
const r = useRouter();
console.log(r.query);
return (
<div>
<div>sku: {r.query?.sku}</div>
<div>discount_id: {r.query?.discount_id}</div>
</div>
);
};
export default Page;
Open http://localhost:3000/sku/1234?discount_id=TESTER
Output:

404 Page Being Shown While NextJS Page Is Rendering

I build all of my initial routes for a dynamic slug based on what I have available in my CMS at build time. Then as new CMS data is available, I will generate new pages when they are requested by the user.
I'm running into an issue where a user might hit /posts/1, but since posts/1 has no CMS data, I'm rendering the 404 page using the notFound boolean inside of getStaticProps. This is what I expect to happen.
Now, if I publish some data to /posts/1 in my CMS, the next time a user hits /posts/1, the API data is fetched in the getStaticProps method, and the page begins to build. The problem is that the user is immediately redirected to the 404 page even though the notFound block is not hit. The router.isFallback flag is also shown as false when it should be true since the page is building. Now, if this user were to refresh their page, they would see the generated page and no longer the 404 page since it is now built.
It seems like Next might route the user's request to the 404 page in the second scenario since it was previously a 404, but is there some way I can "block" the user's request or show my fallback until the page is rendered so that they don't see this 404 when the page is building? This scenario would not happen if the first user did not hit this slug before there was CMS data available.
Here's a simplified example of how I am using getStaticPaths and getStaticProps:
export const getStaticPaths = async (ctx) => {
const myInitialPaths = await fetch('http://my-cms-endpoint.com/initial-paths/');
return {
paths: [
...myInitialPaths
],
fallback: true
}
}
export const getStaticProps = async ({ params }) => {
const myPageData = await fetch('http://my-cms-endpoint.com/page/#id');
if (myPageData) {
return {
props: {
myPageData
}
}
} else {
return {
notFound: true
}
}
}

How to dynamically create subpages/subroutes in NextJS?

I want to create subpages dynamically like
example.com/test/index1
example.com/test/index2
example.com/test/index3
example.com/test/index4
.......
or something like this
example.com/test/[index1]
example.com/test/[index2]
example.com/test/[index3]
The subpages should be created based on the number of indexes. in the base/parent page
I am totally unable to figure out a way to handle something like this
Help would be much appreciated
Nextjs has file system based routing. To create a dynamic route for the app you just need to create a js/ts file with a name similar to [slug].js(where slug will be the route param for the dynamic route) in the pages directory. In that file, you can write all the logic for data-fetching and export a React component as default export which will be used to render the page.
For your use case, the directory structure and some pseudo-code for the page might look something like this
// directory structure
- pages/
- test/
- [slug].js
In [slug].js The example below uses getServerSideProps as data-fetching method which will be used to fetch the data required for the page on request for that page from a client.
// data-fetching methods
export const getServerSideProps = async (ctx) => {
// you have access to the route param slug in the ctx object
const slug = ctx.params.slug
// fetch the data required for the page by a database query or from a remote API
// return the fetched data as props
return {
props: /* fetched-data */
}
}
// the page component
const SomeDynamicPage = (props) => {
// props will contain the data that was returned from the data-fetching method-
// getServerSideProps
return (
<>
<h1>Some page</h1>
<div>
/* some content based on the received props*/
</div>
</>
)
}
export default SomeDynamicPage;
There are additional data-fetching methods (getStaticProps, getStaticPaths, getInitialProps) which may be useful depending on different use cases. Read more about data-fetching and dynamic routes in nextjs docs.

Resources