So I'm working on a site that wants links with the following path:
localhost:3000/visit/:name
To redirect to an external url for example google.com?affiliateID=2. The redirect needs to be nofollow with status code 307.
The app is universal; server-side rendering using express & client-side react, both using a shared routes via react-router.
routes.js
<Route status={307} path="visit/:slug" />
server.js
app.use((req, res) => {
match({routes, location: req.originalUrl}, (err, redirectLocation, renderProps) => {
if (err) {
res.status(500).send(err.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
const html = renderToString(<RouterContext {...renderProps} />)
const isAffiliateLink = renderProps.routes.filter((route) => {
return route.status === 307
}).length > 0
if (isAffiliateLink) {
return res.redirect(307, "http://google.com")
}
const markup = renderToStaticMarkup(<Document html={html} />)
res.status(200).send("<!DOCTYPE html>" + markup)
} else {
res.status(404).send("Not Found")
}
})
})
here I'm checking if the requested route is the /visit/slug by checking the status, 307. If that is the case, it will redirect to the destination. This works.
What I struggle with now however is that I have hundreds of affiliate links, with different URLs and each with a corresponding slug.
What is the best way to programmatically input the right url for the right slug? In the Route I can give a prop
<Route path="/visit/:slug" url="url.com" />
which I can access from server.js, but I'm not sure how to make that one dynamic depending on the slug.
Or should I do an API call to a database on server.js that has all the slugs and their corresponding URL?
Or is there a way I can pass a prop to the Route from a component that is used to click the link? Ie
<AffiliateLink slug={slug} url={url} />
Any help is much appreciated