Created
September 13, 2021 14:06
-
-
Save jordanmaslyn/e30e7ae0910997a3e2da8fa97759c368 to your computer and use it in GitHub Desktop.
Example sitemap sync from WP to NextJS
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 { GetServerSidePropsContext } from "next"; | |
const defaultWpUrl = 'https://example.wpengine.com'; | |
const localHost = 'localhost:3000'; | |
const prodHost = 'example.com'; | |
export default function Sitemap () {}; | |
export const getServerSideProps = async (context: GetServerSidePropsContext) => { | |
let wpUrl = process.env.NEXT_PUBLIC_WORDPRESS_URL ?? defaultWpUrl; | |
if (wpUrl?.endsWith('/')) { | |
wpUrl = wpUrl.substr(0, wpUrl.length - 1); | |
} | |
const { hostname } = new URL(wpUrl); | |
const clientHost = process.env.NODE_ENV === 'development' ? localHost : prodHost; | |
const xmlRes = await fetch(wpUrl + context.req.url); | |
let xml = (await xmlRes.text()); | |
// change server locations to client loctions | |
xml = xml.replace(new RegExp(hostname, 'g'), clientHost); | |
// change client locations for images back to server locations | |
xml = xml.replace(new RegExp(`${clientHost}/wp-content/uploads`, 'g'), `${hostname}/wp-content/uploads`); | |
context.res.setHeader('Content-Type', 'text/xml'); | |
context.res.write(xml); | |
context.res.end(); | |
return { | |
props: {} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment