Next.js Discord

Discord Forum

Redirect on all routes but one

Unanswered
Cape May Warbler posted this in #help-forum
Open in Discord
Avatar
Cape May WarblerOP
Hi, on my page after user registers I want them to finish their profile, for that I put this function in my Layout
export async function redirectCompleteRegistration() {
    const pathname = getPathname();
    if(pathname.startsWith('/onboarding')) return;
    try{
        const user = await getUser();
        if(user?.birthday === null) return redirect(`/onboarding?step=1`);
        if(user?.interests.length === 0) return redirect(`/onboarding?step=2`);
        if(user?.languages.length === 0) return redirect(`/onboarding?step=3`);
    }catch(e){
        throw e;
    }
}

export default function getPathname(withLocale: boolean = true): string {
    const headersList = headers();
    const domain = headersList.get('host') || "";
    const fullUrl = headersList.get('referer') || "";
    let pathname = fullUrl.replace(new RegExp(`(.+)${domain}\/`), "");
    if(!withLocale)
        return pathname;
    
    for(let locale of locales){
        pathname = pathname.replace(`${locale}`, "");
    }
    return pathname;
}

Problem is that my getPathname function is not perfect and it doesn't update immediately so redirect happens 20 times or so. How can I implement this redirect? How can I get pathname in the server component?

3 Replies

Avatar
I want them to finish their profile, for that I put this function in my Layout
You dont need to get the pathname to do user onboarding
just check if user has done onboarding and if not redirect to /onboarding?step=1 etc
async function getUserSession() {
  const user = await getUser();
  if(user?.birthday === null) return redirect(`/onboarding?step=1`);
  if(user?.interests.length === 0) return redirect(`/onboarding?step=2`);
  if(user?.languages.length === 0) return redirect(`/onboarding?step=3`);
}