Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom routing with nextjs?

I have a component which checks a path name and acts on it:

  const router = useRouter();
  const path = router.pathname;//props.location.pathname;

  const p = path.split('/').filter((s) => s !== "")
  let submissionId = p[0] == 's' && p[1]
  const submission = useQuery(SUBMISSION, {
    variables: {
      id: submissionId
    },
    skip: submissionId === false
  })

This works fine in a bog standard react app but nextjs redirects toa 404.

Is tehre a way to set up a pattern for nextjs to ignore none-existant routes and allow the component code to handle it?

like image 976
meds Avatar asked Jul 25 '19 13:07

meds


People also ask

How does routing work in Nextjs?

Next. js has a file-system based router built on the concept of pages. When a file is added to the pages directory, it's automatically available as a route. The files inside the pages directory can be used to define most common patterns.

How do I create a nested route in next JS?

Create a new page named article. js inside the pages folder. Users can implement nested routes by simply nesting folders inside the pages folder just make sure that the file and folder name are the same. Now if you navigate to the URL localhost:300/article/competitive-programming you will see the desired results.

Can you do client-side rendering with Nextjs?

Unlike the server-side rendering APIs, you can use client-side data fetching at the component level.


2 Answers

I'm not sure I've understood clearly what you want, but you need to have defined page in the pages folder if you don't want Next.js to redirect to 404. However, you could use dynamic routes to make component which will do what you want.

Create a file named [dynamic].js in the pages folder:

import React from 'react'
import { useRouter } from 'next/router'

const Dynamic = () => {
  const router = useRouter();
  const { dynamic } = router.query;

  return (
    <div>
      My dynamic page slug: {dynamic}
    </div>
  )
}

export default Dynamic

And you can link to it like this:

<Link href="/[dynamic]" as="/dynamic-page-slug">
  <a>Link to my Dynamic Page</a>
</Link>
like image 78
Spartacus Avatar answered Oct 01 '22 03:10

Spartacus


If you are using zeit now v2 then you can check out the Wildcard Routes here.

Basically in your now.json will have a filesystem handler and a wildcard handler as below

{
  "routes": [
    { "handle": "filesystem" },
    { "src": "/.*", "status": 404, "dest": "SOME_PAGE_HERE" } // <-- this is where all the non-existent routes will be routing to

  ]
}

Just replace the SOME_PAGE_HERE with your route as what you have declared in exportPathMap from the file next.config.js. Example: /contact, about-us and so on.

like image 42
xun Avatar answered Oct 01 '22 04:10

xun