Embedded Values in router

We want to dynamically set a path based on the value of an inbound cookie, so were looking at Layer0 Router Embedded Values

Which says “You can inject values from the request or response into headers or cookies as template literals”

However, we want to use the value of the cookie as part of a redirect path - something like:

({ redirect }) => {    
  redirect('https://www.example.com/${req:cookie:test}', 301)

However doing exactly that results in the following:
location: https://www.example.com/$%7Breq:test%7D

So we ended up using compute to parse the cookies from request.headers.cookie - just want to see if there is a way to utilize the cookie directly in the redirect path without needing to go into compute.

We need to do some further manipulation of the string so it may need compute regardless, so just looking for future info since something seems to be happening with that string in the above example (curlybraces are encoded and the word cookie gets eaten)

did some more testing
I found that this works:

({ setResponseHeader }) => {    
  setResponseHeader('Location', 'https://www.example.com/${req:cookie:test}')

So redirect and setResponseHeader treat those embedded values differently.

So 3 questions:

  1. Is it expected that the embedded values are not available in redirect?

  2. If we decided to go the route of manually setting the Location header, is there a way to set the status code without having to use transformResponse or compute to avoid utilizing serverless for something so trivial?

  3. if we do use compute or transformResponse is the req:cookie object used for those embedded values available, or do we need to manually convert it from a string via request.headers.cookie ?

1 Like

Got some answers:

  1. It was not “expected” for redirect to not include the embedded values, so will be looked into by the platform team. For the time being, use embedded values in header and cookies directly only.

  2. This can be done using send, ex:

({ setResponseHeader, send }) => {    
  setResponseHeader('Location', 'https://www.example.com/${req:cookie:test}')
  return send("", 301, 'Permanently Relocated')

  1. We don’t have access to assign ${req:cookie:value} at the compute level directly (however it can still be used in headers and cookies), but can easily parse it out with the following regex:
let cookieName = 'test';
let cookieValue = request.headers['cookie'].match('(^|;)\\s*' + cookieName +'\\s*=\\s*([^;]+)')?.pop() || ""