Search code examples
next.jscustom-error-pages

Redirect to 404 when custom [slug] is not found in Next JS


I'm surprised I can't find this anyway but here is my issue. I have a Next JS site with the path /location/[location].js The page looks pretty basic

import { nodes } from '../../components/data/nodes'

export default function Location() {
    const router = useRouter()

    useEffect(() => {
         //Do various things   
    }, [])
   
    return (
        <Layout>
             ...My website...
        </Layout>
    )
}

and nodes looks like this

export const nodes = [
{
    id: 'Test1'
}, {
    id: 'Test2'
}, {
    id: 'Test3'
}]

So how can I say if my [location] slug does not match any node id's go to the 404 page? I tried some janky garbage that just feels wrong and throws console errors:

var counter = 1
  for (var node of nodes) {
    if (router.query.location == node.id) {
      break
    } else if (counter++ >= nodes.length) {
      return <Error statusCode={404} />
    }
  }

Can someone help me work this out. Thanks


Solution

  • I'd prefer you to use getStaticProps & getStaticPaths In order to solve this problem. You can use the getStaticProps to fetch the static props. and to define what paths are valid you can use getStaticPaths and load the paths from your nodes variable. If the path doesn't exist you can then simply return a 404 error instead of props

    Please refer the official document of Next.js to know more about the getStaticProps & getStaticPaths