Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created June 6, 2023 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillermodlpa/071c3b12782228852748ae37301e2999 to your computer and use it in GitHub Desktop.
Save guillermodlpa/071c3b12782228852748ae37301e2999 to your computer and use it in GitHub Desktop.
Next.js API route that fetches a page from another site and renders it. Combined with a rewrite fallback rule, this can help integrate pages from a CMS into a Next.js app
import type { NextApiRequest, NextApiResponse } from 'next';
function replaceUrlsInHtmlPage(htmlPage: string, urls: string[], newUrl: string) {
return urls.reduce((memo, url) => memo.replace(new RegExp(url, 'g'), newUrl), htmlPage);
}
/**
* This endpoint is used as a fallback for any route that is not handled by Next.js.
* This way, we can mix a marketing site hosted in WordPress and the app in the same domain
*/
export default async function marketingSiteRender(req: NextApiRequest, res: NextApiResponse) {
const requestedPath = req.query.path as string;
const WORDPRESS_URL = process.env.WORDPRESS_URL;
const APP_URL = process.env.APP_URL;
if (!WORDPRESS_URL) {
throw new Error('WORDPRESS_URL is not defined');
}
if (!APP_URL) {
throw new Error('APP_URL is not defined');
}
const response = await fetch(`${WORDPRESS_URL}/${requestedPath}`);
const htmlPage = await response.text();
const htmlPageWithUrlReplacement = replaceUrlsInHtmlPage(
htmlPage,
[
WORDPRESS_URL,
// account also for links pointing to www, as it's a normal thing that can happen when editing in the CMS
WORDPRESS_URL.replace('https://', 'https://www.'),
],
APP_URL,
);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.write(await htmlPageWithUrlReplacement);
res.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment