Created
June 6, 2023 15:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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