Any UID renders, even if the page does not exist in Prismic

I have created two test blog posts in our dashboard which I want to test in our SvelteKit app. Following the guide, I am able to generate the UID from the pages, but when I type in any param for a page that does not exist, it still renders instead of redirecting to a 404 with a simple try-catch. Could use some guidance on this. Code below as well as screenshot.

<script context="module">
    import Client from "../../../utils/client";

    export async function load({ page }) {
        try {
            const { uid } = page.params;
            const document = await Client.getByUID("blog_post", uid);
            return {
                props: {
                    document,
                    uid,
                },
            };
        } catch (error) {
            return {
                status: 404,
                error: "Post not found",
            };
        }
    }
</script>

<script>
    export let document, uid;
    console.log(uid);
    console.log(document);
</script>

<h1>{uid}</h1>

Hello @teddy_stanowski

Thank you for reaching out to us.

try....catch block works in case there are error returns from the async....await query. In Prismic, if a document is not found in the query in Client.getByUID, it returns undefined but does not throw any error.
For handling 404 here, you need to use if....else block something like this:

<script context="module">
    import Client from "../../../utils/client";

    export async function load({ page }) {
            const { uid } = page.params;
            const document = await Client.getByUID("blog_post", uid);
            if(document){            
              return {
                props: {
                    document,
                    uid,
                  },
               };
            } else {
               return {
                   status: 404,
                   error: "Post not found",
               };
           }
       }
</script>

Please let me know if this still does not solve the issue.

Thank you,
Priyanka

Funny enough I just got it working through a conditional earlier so thanks for validating that solution!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.