Skip to content

Instantly share code, notes, and snippets.

@neilkillen
Last active August 18, 2022 16:10
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 neilkillen/8741dbe62d3537029f061dce9ebae804 to your computer and use it in GitHub Desktop.
Save neilkillen/8741dbe62d3537029f061dce9ebae804 to your computer and use it in GitHub Desktop.
/**
** The handleStoreRequest Function is used to rewrite store url
** based on user information stored in Sitecore Personalize
* @param req
* @returns NextResponse with a rewrite set
*/
async function handleStoreRequest(req: NextRequest) {
// Check if we have a browserId in the request cookie collection
let browserId = getCookie(req.headers.get('cookie'), browserIdCookieName)
let hasBrowserIdCookie = !!browserId
if(!hasBrowserIdCookie){
browserId = await getBrowserRef()
}
// Attempts to retrieve Guest information from Sitecore Personalize
let guest = await getGuestInformation(browserId);
if(!!guest)
{
// Rewrite store url based on guest gender stored in CDP
let shopRoute = shopRoutes.find(route => route.key==guest.gender)?.value
|| req.nextUrl.pathname
req.nextUrl.pathname = shopRoute
}
const response = NextResponse.rewrite(req.nextUrl)
console.log(`HandleStoreRequest - Rewrite path : ${req.nextUrl.pathname}`);
// Add Cookie to response if it did not already exist
if(!hasBrowserIdCookie){
response.cookies.set(browserIdCookieName, browserId, cookieOptions);
}
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment