#Incremental Static Regeneration on product page

7 messages · Page 1 of 1 (latest)

marsh wyvern
#

As per my understanding the products pages are generated at build and run time. My application has over 2K sellers and over 10K products so changes happen a lot and product pages are often outdated as the data gets updated on the Medusa Admin. Has anyone used ISR on Next?

quick badger
#

I am implemeting it atm

#

I am running into the same issue, we have more than 100k products

faint void
#

@marsh wyvern You can subscribe to product.created,product.updated,variant.updated events etc and fire an axios request to ISR endpoint in Next.js where you will trigger the revalidation.

#

An example:

// Medusa backend
//src/subscribers/product-revalidator.js
import axios from 'axios';

const SUPER_SECRET_REVALIDATION_KEY = process.env.STOREFRONT_REVALIDATE_SECRET;

class ProductRevalidator {
  constructor({
    productService,
    eventBusService,
  }) {
    this.productService_ = productService;

    eventBusService.subscribe('product.updated', this.revalidateProduct);
    eventBusService.subscribe('product.created', this.revalidateProduct);
    eventBusService.subscribe('product-variant.created', this.revalidateProduct);
    eventBusService.subscribe('product-variant.updated', this.revalidateProduct);
    eventBusService.subscribe('product-variant.deleted', this.revalidateProduct);
  }

  revalidateProduct = async (data) => {
    const productId = data.product_id || data.id;
    const product = await this.productService_.retrieve(productId, {
      relations: ['collection'],
    });

      return axios.post(
        `${process.env.STORE_CORS}/api/products/revalidate?productHandle=${product.handle}&collectionHandle=${product.collection.handle}&secret=${SUPER_SECRET_REVALIDATION_KEY}`
      );
  };
}

export default ProductRevalidator;
#
/// nextjs api/products/revalidate.js
export default async function handler(req, res) {
  if (req.query.secret !== process.env.STOREFRONT_REVALIDATE_SECRET) {
    return res.status(401).json({ message: 'Invalid token' });
  }

  try {
    if (req.query.productHandle && req.query.collectionHandle) {
      await res.revalidate(`/product/${req.query.productHandle}`);
      // if you want to revalidate collection page
      await res.revalidate(`/collection/${req.query.collectionHandle}`);
      // Some other pages if you want to revalidate, like main page:
      await res.revalidate('/');
      return res.json({ revalidated: true });
    }
  } catch (err) {
    console.error(err);
    return res.status(500).send('Error revalidating');
  }
}