Next.js Discord

Discord Forum

redirect -> redirect does not update the URL

Unanswered
American posted this in #help-forum
Open in Discord
AmericanOP
Hello!

I have a situation where I'm redirecting from a server action to a route /logged-in which in turn redirects the user where it should actually go. This causes the URL in the browser to get stuck on /logged-in which in turn is affecting forms with actions.

Is this a bug or should I just refactor?

5 Replies

AmericanOP
Oh, I was using redirect from next/navigation in the route as well
@American Hello! I have a situation where I'm redirecting from a server action to a route `/logged-in` which in turn redirects the user where it should actually go. This causes the URL in the browser to get stuck on `/logged-in` which in turn is affecting forms with actions. Is this a bug or should I just refactor?
You can't redirect from within a server action, but you can redirect based on the response of the server action

import { redirect } from 'next/navigation'
 
async function fetchTeam(id) {
  const res = await fetch('https://...')
  if (!res.ok) return undefined
  return res.json()
}
 
export default async function Profile({ params }) {
  const team = await fetchTeam(params.id)
  if (!team) {
    redirect('/login')
  }
 
  // ...
}

https://nextjs.org/docs/app/api-reference/functions/redirect#example
AmericanOP
You can't redirect from within a server action
Yeah you can
"use server"
export async function testAction() {
  redirect("/foo");
}


and then just
<form action={testAction}>
  <button type="submit">Test</button>
</form>