Next.js Discord

Discord Forum

how to redirect user back to where he came from after auth???

Answered
Chinese Chongqing Dog posted this in #help-forum
Open in Discord
Chinese Chongqing DogOP
Hey, im new and have a issue where i wasnt able to find the solution. i have a /dashboard route and a /dashboard/account route which i protect by authenticating the user everytime he makes a new request, now my issue is that if i redirect the user to api/refresh to refresh his access token i dont know how after its finished i can redirect him back to where he came from (/dashboard or /dashboard/account), here is my relevant code:

dashboard/layout.tsx:
export default async function DashboardLayout({ children }: { children: ReactNode }) {

  const currentPath = "placeholder"
  await verifySession(currentPath)
  
  return (
    <section>
      <main>{children}</main>
    </section>
  )
}

- on every request in the /dashboard route run verifySession
- issue here is that i dont know how to get the actual currentPath.

lib/dal.tsx (verifySession)
export async function verifySession(currentPath: string) {

  if (accessToken) {
    // unrelated logic
  }

  // If access token invalid but refresh token exists → redirect browser to refresh route
  if (refreshToken) {
    redirect(`/api/refresh?redirectTo=${encodeURIComponent(currentPath)}`);
  }

  redirect('/login');
}

- redirect the user to api/refresh so his access token gets refreshed


api/refresh.tsx
export async function GET(req: NextRequest) {

  // unrelated logic

  const redirectTo = req.nextUrl.searchParams.get('redirectTo') || '/dashboard';

  const response = NextResponse.redirect(new URL(redirectTo, req.url));

  // Set new access token cookie in browser
  response.headers.append('Set-Cookie', createAccessCookie(accessSession.id));

  return response;
}

- here we assign a new access token and redirect back

in the layout file i already tried getting the path trough usePathname tho this is clientside only, then i tried using ...props/[[...slug]] which dont work in a layout, also tried headers which didnt work
Answered by Chinese Chongqing Dog
solved setting requestheader x-current-path in the middleware and getting it in verifySession.
View full answer

1 Reply

Chinese Chongqing DogOP
solved setting requestheader x-current-path in the middleware and getting it in verifySession.
Answer