Skip to content

Commit

Permalink
docs(nx-dev): Add 404 for unknown blog urls (#23267)
Browse files Browse the repository at this point in the history
This PR adds the 404 fallback if a user navigates to a specified blog
that does not exist.

Currently, we are showing a 500 error.
  • Loading branch information
ndcunningham committed May 9, 2024
1 parent f489fbe commit bdac1e2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
9 changes: 9 additions & 0 deletions nx-dev/data-access-documents/src/lib/blog.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ export class BlogApi {
return sortPosts(allPosts);
}

getBlogPost(slug: string): BlogPostDataEntry {
const blogs = this.getBlogPosts();
const blog = blogs.find((b) => b.slug === slug);
if (!blog) {
throw new Error(`Could not find blog post with slug: ${slug}`);
}
return blog;
}

private calculateSlug(filePath: string, frontmatter: any): string {
const baseName = basename(filePath, '.md');
return frontmatter.slug || baseName;
Expand Down
23 changes: 14 additions & 9 deletions nx-dev/nx-dev/pages/blog/[slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,19 @@ export default function BlogPostDetail({ post }: BlogPostDetailProps) {

export const getStaticProps: GetStaticProps = async (context) => {
// optimize s.t. we don't read the FS multiple times; for now it's ok
const posts = await blogApi.getBlogPosts();
const post = posts.find((p) => p.slug === context.params?.slug);

return {
props: {
post,
},
};
// const posts = await blogApi.getBlogPosts();
// const post = posts.find((p) => p.slug === context.params?.slug);
try {
const post = await blogApi.getBlogPost(context.params?.slug as string);
return { props: { post } };
} catch (e) {
return {
notFound: true,
props: {
statusCode: 404,
},
};
}
};

export const getStaticPaths: GetStaticPaths = async () => {
Expand All @@ -60,5 +65,5 @@ export const getStaticPaths: GetStaticPaths = async () => {
params: { slug: post.slug },
}));

return { paths, fallback: false };
return { paths, fallback: 'blocking' };
};

0 comments on commit bdac1e2

Please sign in to comment.