platforms icon indicating copy to clipboard operation
platforms copied to clipboard

CORS error when trying to trigger custom revalidation for ISR pages

Open MarkwinVI opened this issue 1 year ago • 0 comments

Hey, I'm trying to do custom revalidation for my static pages, and I've followed the example given in the project, but every time I try to validate I get a CORS error

Screenshot 2022-07-24 at 22 23 11 Screenshot 2022-07-24 at 22 30 22

Essentially, I'm trying to revalidate a page on a custom domain from the main app (a different domain).

My revalidate client fetch call (called from the core app and not the subdomain)

  if (subdomain) {
        await revalidate(
          `https://${subdomain}.myapp.com`, // hostname to be revalidated
          subdomain, // siteId
          "/"
        );
}

The revalidate function that calls the fetch

export async function revalidate(
  hostname: string, // hostname to be revalidated
  siteId: string, // siteId
  slug: string // slugname for the post
) {
  const urlPaths = [`/_sites/${siteId}/${slug}`, `/_sites/${siteId}`];
  try {
    await Promise.all(
      urlPaths.map((urlPath) =>
        fetch(`${hostname}/api/revalidate`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            urlPath,
          }),
        })
      )
    );
  } catch (err) {
    console.error(err);
  }
}

The pages/api/revalidate.ts

import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { urlPath } = req.body;
  try {
    await res.revalidate(urlPath);

    return res.status(200).json({
      message: "OK",
    });
  } catch (error) {
    res.status(500).json({
      message: `Failed to revalidate "${urlPath}"`,
    });
  }
}

Through some googling, I found that you cant set CORS access headers for all of your APIs by following this article https://vercel.com/support/articles/how-to-enable-cors

My next.config.js

module.exports = {
  reactStrictMode: true,
  async headers() {
    return [
      {
        // matching all API routes
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
        ]
      }
    ]
  }
}

But even so every time I try to call the revalidate API I get the following errors as you can see in the first images.

Any help would be appreciated!

MarkwinVI avatar Jul 24 '22 19:07 MarkwinVI