I have a product page at /products/[slug].js
and I use Incremental Static Generation for a wordpress/graphql site:
export async function getStaticProps(context) {
const {params: { slug }} = context
const {data} = await client.query(({
query: PRODUCT_SLUG,
variables: { slug }
}));
return {
props: {
categoryName: data?.productCategory?.name ?? '',
products: data?.productCategory?.products?.nodes ?? []
},
revalidate: 1
}
}
export async function getStaticPaths () {
const { data } = await client.query({
query: PRODUCT_SLUGS,
})
const pathsData = []
data?.productCategories?.nodes && data?.productCategories?.nodes.map((productCategory) => {
if (!isEmpty(productCategory?.slug)) {
pathsData.push({ params: { slug: productCategory?.slug } })
}
})
return {
paths: pathsData,
fallback: true,
}
}
Everything works as expected except one thing. If I delete a product from wordpress which was previously published, NextJs serves the cached page instead of showing 404 - Not found page, and I think this is how it is supposed to work, meaning that if something isn't rebuilt, show the previous (stale) page.
But how can I completely remove the cache for a specific product which has been deleted and it is not fetched again from the PRODUCT_SLUGS query ?
I have read the fallback options: true, false, blocking but none of them seems to work.
Is there a solution to this, either a next.config.js configuration or another work around ?
So I ran into this same issue, although I am using GraphCMS. So here is what you need to do to fix:
export async function getStaticProps(context) {
const {params: { slug }} = context
const {data} = await client.query(({
query: PRODUCT_SLUG,
variables: { slug }
}));
if (!data) {
return {
notFound: true
}
} else {
return {
props: {
categoryName: data?.productCategory?.name ?? '',
products: data?.productCategory?.products?.nodes ?? []
},
revalidate: 1
}
}
}
You need to return notFound: true in getStaticProps
notFound - An optional boolean value to allow the page to return a 404 status and page.
See this page in the docs https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
Then in getStaticPaths change fallback to fallback: "blocking". If you keep fallback: true it is going to serve the stale page since that built successfully.
I think this is possible starting from next#12.1.x using this feature On-demand Incremental Static Regeneration
https://nextjs.org/blog/next-12-1#on-demand-incremental-static-regeneration-beta
basically you can define an api path in this way
// pages/api/revalidate.js
export default async function handler(req, res) {
// Check for secret to confirm this is a valid request
if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
return res.status(401).json({ message: 'Invalid token' })
}
const PRODUCT_SLUGS = req.query.product_slug;
try {
await res.unstable_revalidate(`/products/${PRODUCT_SLUGS}`)
return res.json({ revalidated: true })
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send('Error revalidating')
}
}
Using this api path you can invalidate the cache for a specific product
Related
Is there any why to show loading screen while fetching API data using getStaticProps in next js?
export async function getStaticProps() {
const data = await fetch(API_END_POINT);
return {
props: {
data
}
}
}
getStaticProps runs at build time so there is no need for the loading screen since the data will always be available (statically generated).
However, there is another option: getStaticPaths
In combination with fallback pages.
Basically there is a mix of static and server rendered pages (but there is no request and response objects)
// pages/posts/[id].js
import { useRouter } from 'next/router'
function Post({ post }) {
const router = useRouter()
// If the page is not yet generated, this will be displayed
// initially until getStaticProps() finishes running
if (router.isFallback) {
return <div>Loading...</div>
}
// Render post...
}
// This function gets called at build time
export async function getStaticPaths() {
return {
// Only `/posts/1` and `/posts/2` are generated at build time
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
// Enable statically generating additional pages
// For example: `/posts/3`
fallback: true,
}
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return {
props: { post },
// Re-generate the post at most once per second
// if a request comes in
revalidate: 1,
}
}
export default Post
Just make sure to add getStaticPaths with fallback equal to true. See example below
export async function getStaticPaths() {
return {
paths: [],
fallback: true,
}
}
then in the component(example a post page component), add a check if router isFallback is true. See below example
import { useRouter } from 'next/router'
function Post({ post }) {
const router = useRouter()
// If the page is not yet generated, this will be displayed
// initially until getStaticProps() finishes running
if (router.isFallback) {
return <div>Loading...</div>
}
// Render post...
}
For example, I have a dynamic route /blog/[article-id].
When visiting an existing blog post /blog/id-that-exist, it works as expected, and now I want to handle the case /blog/id-that-does-not-exist properly.
The code in /blog/[id].jsx looks something like:
export const getStaticPaths async () => {
return {
fallback: true,
paths: (await sequelize.models.Article.findAll()).map(
article => {
return {
params: {
pid: article.slug,
}
}
}
),
}
}
export const getStaticProps async () => {
// Try to get it from the database. Returns none if does not exist.
const article = await sequelize.models.Article.findOne({
where: { slug: pid },
});
return { props: { article: article } };
}
const ArticlePage = (props) => {
// This can happen due to fallback: true while waiting for
// a page that was not rendered at build time to build.
const router = useRouter()
if (router.isFallback) {
return <div>loading</div>;
}
return (
<div>{props.article.body}</div>
);
};
export const getStaticPaths = getStaticPathsArticle;
export const getStaticProps = getStaticPropsArticle;
export default ArticlePage;
I saw this related question: How to handle not found 404 for dynamic routes in Next.js which is calling API? but I'm not sure if it's the same as I'm asking here, as this does not depend on any external API being used.
notFound: true from Next.js 10
Starting in Next.js 10, we can do:
export const getStaticProps async () => {
// Try to get it from the database. Returns none if does not exist.
const article = await sequelize.models.Article.findOne({
where: { slug: pid },
});
if (!article) {
return {
notFound: true
}
}
return { props: { article: article } };
}
as documented at: https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
When notFound is returned, the rendering function ArticlePage just never gets called, and the default 404 page is returned instead.
Note however that ArticlePage did get
For some reason in development mode:
I don't get the expected 404 HTTP status code
ArticlePage, so if you forgot to handle the fallback case, the it might crash due to missing properties
which was confusing me a bit. But in production mode, everything works as expected.
Workaround before Next.js 10
As shown https://github.com/vercel/next.js/discussions/10960#discussioncomment-1201 you could previously do something like:
const ArticlePage = (props) => {
if (!props.article) {
return <>
<Head>
<meta name="robots" content="noindex">
</Head>
<DefaultErrorPage statusCode={404} />
</>
}
return (
<div>{props.article.body}</div>
);
};
but this is not ideal because it does not set the HTTP return code correctly I believe, and I don't know how to do it.
Tested on Next.js 10.2.2.
I've read your answer regarding the solution after Next.js v.10, but I didn't get what was the problem in showing the expected http 404 code during development.
I use Next.JS v.12 and I get the expected 404 normally in development
import { GetStaticPaths, GetStaticProps } from 'next'
import { useRouter } from 'next/router'
import { ParsedUrlQuery } from 'querystring'
import Loading from '../../components/loading'
export const getStaticPaths: GetStaticPaths = async () => {
//your paths
return { paths, fallback: true }
}
export const getStaticProps: GetStaticProps = async ({ params }: { params?: ParsedUrlQuery }) => {
//get your props
if (!target){
return {notFound: true}
}
return { props: { ... }, revalidate: 86400}
}
function Index({ ... }) {
const router = useRouter()
if (router.isFallback) {
return <Loading />
}
return (
<div>
//my content
</div>
)
}
export default Index
When the target isn't found, it renders my custom 404 component in pages/404.tsx if I created one or just the default 404 page.
This should work normally during development and production.
This question already has an answer here:
How to add new pages without rebuilding an app with +150k static pages?
(1 answer)
Closed last year.
I am using ISR but adding new blogs, editing doesn't seem to be working on the production.
// /blogs/[slug].js
export async function getStaticProps({ params }) {
const res = await api.get(`/api/v1/blogs/${params.slug}`);
const blog = res.data;
return { props: { blog }, revalidate: 60 };
}
export async function getStaticPaths() {
const res = await api.get("/api/v1/blogs");
const blogs = res.data;
const paths = blogs.map((item) => ({
params: { slug: item.slug },
}));
return { paths, fallback: false };
}
You'll want to set your fallback value to either true or 'blocking' so that new pages can be generated. Otherwise, paths that don't exist at build time will simply 404.
export async function getStaticPaths() {
// Existing code
return { paths, fallback: true };
}
The Issue
I cannot query the API by slug, it must be by id. An KeystoneJS headless CMS provide the data via API and my NextJS should use this data in a static generated Next.js app.
Keystone API must be queried like this:
All Posts: (ALL_POSTS_QUERY)
query {
allPosts {
id
slug
title
}
}
Single Post: (POST_QUERY)
query {
Post(where: { id: $id }) {
title
body
}
}
I do use Apollo Client to connect to the API endpoint.
A query for an individual post must be formatted as described above, with an id variable and that's what seems to be the issue. I need to generate static pages by slug and not by id.
The functions
getStaticPaths()
export const getStaticPaths = async () => {
const { data } = await apolloClient.query({
query: ALL_POSTS_QUERY,
});
return {
paths: data.allPosts.map(({ id, slug }) => ({
params: { slug: slug },
})),
fallback: false,
};
};
getStaticProps()
export const getStaticProps = async ({ params }) => {
const id = params.id;
const { data } = await apolloClient.query({
query: POST_QUERY,
variables: {
id,
},
});
return {
props: {
term: data.Post,
},
};
};
More info about KeystoneJS generated APIs.
Please help
I'm very new to developing so my understanding of this is still basic. Apologies if I've misunderstood the logic. Please can anyone help me with where I'm going wrong with my functions? I wasn't able to find anyone else trying to build dynamic routes by slug but querying the API by id to retrieve that post's data.
Your problem is that you want to access the prop id of params, but params.id simply does not exist. What exists is params.slug. If you want to pass through the id, then change your code to this:
export const getStaticPaths = async () => {
const { data } = await apolloClient.query({
query: ALL_POSTS_QUERY,
});
return {
paths: data.allPosts.map(({ id, slug }) => ({
params: { id },
})),
fallback: false,
};
};
Now you are passing through the id instead of the slug and should be fine.
I am using next.js 10 and have a [slug] page which creates dynamic pages from Contentful CMS.
I am changing the slug inside CMS and run next dev the old slug correctly returns 404 and the new slug works.
However when I build and run next start the old slug still returns a cached page, the new slug works properly.
I am returning revalidate 10 and have assumed the page should refresh after 10sec
export const getStaticProps: GetStaticProps<SlugRoutePageProps> = async ({
params,
}) => {
....
....
const pageData = await getPageData(params.slug)
if (pageData.total === 0) return { notFound: true }
return {
props: {
pageType: "DynamicPage",
pageProps: {
pageData,
},
revalidate: 10,
},
}
}
in getStaticPaths I have fallback: "blocking", also tried fallback: true with no difference.
Edit:
getPageData is a basic call to the contentful api - no caching
const getPageData = async (
slug: string,
): Promise<FetchPagesResult> => {
const client = createContentfulClient()
return client.getEntries<Page>({
content_type: "page",
"fields.slug": slug,
include: 5,
order: "-sys.updatedAt",
limit: 1,
})
}