Created
September 23, 2022 15:01
-
-
Save jordanmaslyn/4c52c6357b3f12878c1a40ca48962b5f to your computer and use it in GitHub Desktop.
Fetch redirects at build-time from the Redirection plugin in WordPress, taken from JonnyTurbo in the Headless WP Discord - https://discord.com/channels/836253505944813629/836658991253553172/1012026516718223492
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
async function fetchWordPressRedirects() { | |
if(!process.env.WORDPRESS_USERNAME | |
|| !process.env.WORDPRESS_PASSWORD | |
|| !process.env.REDIRECTION_API_ENDPOINT) { | |
return []; | |
} | |
const base64UsernamePasswordToken = Buffer.from( | |
process.env.WORDPRESS_USERNAME + ':' + process.env.WORDPRESS_PASSWORD | |
).toString('base64'); | |
const resp = await fetch(process.env.REDIRECTION_API_ENDPOINT, { | |
headers: { | |
Authorization: `Basic ${base64UsernamePasswordToken}` | |
} | |
}); | |
const data = await resp.json(); | |
if(!Array.isArray(data.items)) { | |
return []; | |
} | |
return data.items | |
.filter((redirection) => redirection.action_type === 'url') | |
.map((redirection) => ({ | |
source: redirection.url, | |
destination: redirection.action_data.url, | |
permanent: redirection.action_code === 301 | |
})); | |
} |
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
module.exports = { | |
async redirects() { | |
const wordPressRedirects = await fetchWordPressRedirects(); | |
return wordPressRedirects; | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment