4

I'm currently trying to make a dynamic route with Next.js 13 with app folder, my request is that I want to define some static routes and if the slug does not match with what I put, it'll return a 404 page

Here is what I did with Next version at 13.0.5 and pages folder and this was working great, if I'm going to an unexisting page like /pages/post/foo, I'm redirected to 404 page

// pages/post/[id].tsx
import { useRouter } from "next/router";

const Post = () => {
  const router = useRouter();
  const { id, foo } = router.query;

  return (
    <div>
      <p>Post: {id}</p>
    </div>
  );
};

export const getStaticProps = () => ({
  props: {},
});

export const getStaticPaths = () => ({
  paths: [{ params: { id: "abc" } }, { params: { id: "abcd" } }],
  fallback: false,
});

export default Post;

Now I'm trying to do the same with app folder and this version of Next.js 13.4.4

// app/[locale]/post/[id].tsx
export const dynamicParams = false;
export const generateStaticParams = async () => [{ id: "abc" }, { id: "abcd" }];

const Post = ({ params: { id } }) => (
  <div>
    <p>Post: {id}</p>
  </div>
);

export default Post;

But the issue is that it's not working at all, I mean by that that the dynamic route is working but if I try something like /post/foo, it's not showing a 404 page I'm using next-intl for the locale change

A solution I thought was to do this

import { notFound } from "next/navigation";

const Post = ({ params: { id } }) => {
  if (!['abc', 'abcd'].includes(id)) notFound();

  return (/* ... */);
};

But I wanted to know if there was a better solution, thanks in advance!

3
  • Does this answer your question? How to redirect to the 404 Not Found Page in the app folder of Next.js? Commented Aug 9, 2023 at 17:16
  • That's already what I proposed at the end but I don't know how this works, I mean by that, will the page will be pre-charged with SSR like that and SEO works correctly for /post/abc and /post/abcd with that solution ? I don't think so :/ Thanks for the answer though! Commented Aug 10, 2023 at 8:08
  • Yeah, I think as there is no use client in the picture, the page will be a pur sever side component. Commented Aug 10, 2023 at 9:17

3 Answers 3

7

To throw a "not found" page in Next.js using App Router for dynamic URLs, you would do this:

import { notFound } from 'next/navigation';

type Params = {
  id: string;
};

export default function YourPage({ params }: { params: Params }) {
  // quick for demo purposes
  if (params.id === '123') {
    notFound();
  }

  return (
    <p>Look at this page, this page is amazing!</p>
  );
}

See the official Next.js documentation here: https://nextjs.org/docs/app/api-reference/functions/not-found

Sign up to request clarification or add additional context in comments.

3 Comments

Oh thank you, let's say this is what I have done, now Google Console is telling me that the page won't be indexed because of a redirection, do you know what to do in this situation?
@Bambou I think that question would warrant its own topic. But 404 pages should not be indexed, generally speaking, so that's a good thing.
Mmmm IDK because I think that my pages are not indexed because of Next not working correctly, my page not indexed is not a 404 but the page I want to be indexed :/
3

https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config

https://nextjs.org/docs/app/api-reference/file-conventions/not-found

You can use a combination of dynamic and dynamicParams to achieve this effect in combination with a not-found.tsx in the folder your route lives at.

// [id]/page.tsx

export default function IdPage({ id }: any) {
  return <>Something here...</>;
}

export async function generateStaticParams() {
  return ['1', '2', '3'].map((id) => ({
    id
  }));
}

export const dynamic = 'force-static';
export const dynamicParams = false;

5 Comments

It works fine when launching yarn dev but it doesn't work when doing yarn build with I add dynamic and dynamicParams :/
@Bambou What build errors are you getting?
I don't have build errors but my route is always redirecting to 404 even though it shouldn't with the IDs inside generateStaticParams and I can't figure why
You may not need export const dynamicParams = false;. Based on the documentation, setting dynamic to force-static automatically sets dynamicParams to false. In my project I had to use both and it might have something to do with the NextJS 13 version. That combination worked for me on version 13.4.19. I would play around with dynamic/dynamicParams and update the version.
I tried your solution but it did unfortunately not work, when doing yarn start, all pages are 404 (even the pages that should return a status 200) but when doing yarn dev, my page is still rendered even with the pages that shouldn't be rendered, now I have issue with Google because they say my page is doing redirection and they can't crawl it :(
-2

If you are using getStaticProps :

    export const getStaticPaths: GetStaticPaths = async ()=> {
        return {
            paths: [], //you can define your paths
            fallback: "blocking"
        }
    }

    export const getStaticProps: GetStaticProps = async (context) => {
       const slug = context.params?.slug as string;
       const posts = getTutorialBySlug(slug) ?? null;
    
       if (!posts) {
           return {
               notFound: true,
           };
       }
    
       return {
           props: {
               posts: posts,
           },
       };
    };

If you are using get ServerSideProps :

    export const getServerSideProps: GetServerSideProps = async (
      context
    ) => {
      const slug = context.params?.slug as string;
      const post = getPostBySlug(slug) ?? null;
    
      if (!post) {
        return {
          notFound: true, //redirects to 404 page
        };
      }
    
      return {
        props: {
          post,
        },
      };
    };

2 Comments

Have you read his question? He is using the new app folder of Next.js, where there is none of these function.
As @YoussoufOumar said, I'm using app folder for this one so this will not be working :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.