'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 1:[1]

I'd prefer you to use getStaticProps & getStaticPaths In order to solve this problem. You can use the getSetaticProps 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

Solution 2:[2]

You can easily define a state and according to state render your component.

import Error from "next/error";

// inside functional component
 const [errorCode , setErrorCode] = useState(0);
 const router = useRouter():
 
 useEffect(() => {
  const location =  router.query.location
  const search = nodes.filter(item => item.id === location ):
  if(search.length === 0){
    setErrorCode(404)
  }
 },[])
 
 if (errorCode == 404) {
   return (
      <Error statusCode={errorCode} title="page Not Found" />
   </>
   );
}
return (
  <Layout>
         ...My website...
    </Layout>
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 udoyhasan
Solution 2 Paiman Rasoli