https://www.growthbook.io/ logo
#contributing
Title
# contributing
r

rhythmic-psychiatrist-74694

03/29/2022, 12:59 PM
Hey! Do you have a nice way of updating the attributes of a growthbook instance through the lifetime of a Nextjs app? I currently do it like this
Copy code
export const useSetGrowthbookAttributes = (
  attributes: Record<string, string | number | boolean>
) => {
  const gb = useGrowthBook();
  useEffect(() => {
    gb?.setAttributes(attributes);
  }, []);
};
But would love to hear other ideas!
f

future-teacher-7046

03/29/2022, 1:24 PM
Hi! I think that's generally the right approach when a specific page or component needs to have control over it's attributes . One thing to note is that
setAttributes
completely overwrites all existing attributes. If you want to be able to set partial attributes, you can do:
Copy code
gb.setAttributes({
  ...gb.getAttributes(),
  ...attributes
})
In a lot of cases, attributes can be set at a higher level, like in
_app.tsx
or in your auth handler. For example, this in _app.tsx will keep a URL attribute up to date as you navigate the app:
Copy code
const router = useRouter()

useEffect(() => {
  const update = (url) => {
    gb.setAttributes({
      ...gb.getAttributes(),
      url: url
    })
  }
  router.events.on('routeChangeStart', update)
  return () => router.events.off('routeChangeStart', update)
}, [])
r

rhythmic-psychiatrist-74694

03/29/2022, 1:47 PM
Nice, thanks! Do you currently support/have a best practice for stickiness in feature/experiment variations when going from an anonymous user to a logged in state? e.g. I can say that I want users to be split by
id
in growthbook, but if I have a page that is shown to both anonymous and logged in users, I want them to have the same experience when logging in. If I generate a random ID when they first land on the page, how do I make sure that they see the same variant when they log in (I would like to tie the userId to
id
when logged in)?
f

future-teacher-7046

03/29/2022, 1:54 PM
We recommend keeping the attributes consistent. So
id
would always be the logged-in user id (or null or empty string when anonymous). And a second
sessionId
or similar would always be set for everyone and based on a cookie or local storage value.
If you split by
id
and it's an anonymous user, they will be excluded from the experiment since that attribute will be null. If you want to run an experiment for everyone, you would choose to split on
sessionId
instead
r

rhythmic-psychiatrist-74694

03/29/2022, 1:57 PM
Yeah that makes sense. So just keep
id
in the attributes after they log in while using the
sessionId
for assigning variants. Thanks!
13 Views