Next.js Discord

Discord Forum

Redirect to 404 on Missing API Data

Unanswered
Black Caiman posted this in #help-forum
Open in Discord
Black CaimanOP
Hi all, I'm currently working on the project page of my portfolio website.

I'm fetching the page data from my CMS (Sanity) which works. However, on invalid links, the fetch function returns null.
When this happens, I want to redirect visitors to the 404 page?

How do I do this through Next? :blob_thonkang:
I know the default 404 page triggers on non-existent routes.

Project > [Project] > page.ts
type ProjectPage = {
  params: { project: string };
};

export default async function Project({ params }: ProjectPage) {
  const slug = params.project;
  const project = await getProject(slug);

  // If project is null, link to 404 page
  return <div>{project.projectName}</div>;
}


Error Message - (See attached)

1 Reply

@Black Caiman Hi all, I'm currently working on the project page of my portfolio website. I'm fetching the page data from my CMS (Sanity) which works. However, on invalid links, the fetch function returns `null`. When this happens, I want to redirect visitors to the 404 page? How do I do this through Next? <:blob_thonkang:753870952709750834> I know the default 404 page triggers on non-existent routes. **Project > [Project] > page.ts** type ProjectPage = { params: { project: string }; }; export default async function Project({ params }: ProjectPage) { const slug = params.project; const project = await getProject(slug); // If project is null, link to 404 page return <div>{project.projectName}</div>; } **Error Message - (See attached)**
'use client';
// Using the router to redirect the user to the 404 page
import { useRouter } from 'next/navigation';
// Returning another component
import NotFound from '@components/not-found.tsx';

type ProjectPage = {
  params: { project: string };
};

export default async function Project({ params }: ProjectPage) {
  const slug = params.project;
  const project = await getProject(slug);

  // Router method
  const router = useRouter();
  if (!project) router.push('/404');
  // Component method
  return project ? <div>{project.projectName}</div> : <NotFound />;
}