meds
meds

Reputation: 22926

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?

Upvotes: 8

Views: 4562

Answers (3)

Jobajuba
Jobajuba

Reputation: 1282

In your server.js, add the following:

// server.js
const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);

app.prepare().then(() => {
    createServer(handler).listen(port, err => {
        if (err) {
            throw err;
        }
        console.log(`> Ready on http://localhost:${port}`);
    });
});

Then in your routes.js file define your custom routes:

// routes.js
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());

routes
    .add('landing', '/')
    .add('profile', '/profile', 'profile');

Upvotes: 1

xun
xun

Reputation: 536

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.

Upvotes: 4

Spartacus
Spartacus

Reputation: 429

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>

Upvotes: 8

Related Questions