import { redirect as nextRedirect, RedirectType } from 'next/navigation'; import Settings from 'settings'; import { headers } from 'next/headers'; import { ServerVariables } from '@akinon/next/utils/server-variables'; import { getUrlPathWithLocale } from '@akinon/next/utils/localization'; import { urlLocaleMatcherRegex } from '@akinon/next/utils'; export const redirect = (path: string, type?: RedirectType) => { const nextHeaders = headers(); const pageUrl = new URL( nextHeaders.get('pz-url') ?? process.env.NEXT_PUBLIC_URL ?? '' ); const currentLocale = Settings.localization.locales.find( (locale) => locale.value === ServerVariables.locale ); const searchParams = new URLSearchParams(pageUrl.search); const callbackUrl = pageUrl.pathname.replace(urlLocaleMatcherRegex, '') + (searchParams.toString() ? `?${searchParams.toString()}` : ''); const redirectUrlWithLocale = getUrlPathWithLocale( path, currentLocale?.value ); const redirectUrl = `${redirectUrlWithLocale}?callbackUrl=${callbackUrl}`; if (type) { return nextRedirect(redirectUrl, type); } else { return nextRedirect(redirectUrl); } };