Next.js Discord

Discord Forum

redirect with after

Answered
Australian Freshwater Crocodile posted this in #help-forum
Open in Discord
Australian Freshwater CrocodileOP
is it possible to use redirect inside after? i want to do something like this:
"use server"

export const serverAction = async () => {
  after(() => { redirect("/") });

  return { success: true };
}

but i'm getting NEXT_REDIRECT error
Answered by Australian Freshwater Crocodile
i managed to do what I wanted by using redirect in finally of trycatch, thanks for the reply, joulev
View full answer

4 Replies

@Australian Freshwater Crocodile is it possible to use redirect inside after? i want to do something like this: ts "use server" export const serverAction = async () => { after(() => { redirect("/") }); return { success: true }; } but i'm getting NEXT_REDIRECT error
… why do you want to redirect in after()? after() is for server side-effects that are run after all client-server interactions have completed, whatever is in after() does not have any effect on the client
@joulev … why do you want to redirect in after()? after() is for server side-effects that are run after all client-server interactions have completed, whatever is in after() does not have any effect on the client
Australian Freshwater CrocodileOP
Well, I have a checkout form:
"use client"

import Form from "next/form"

const CheckoutForm = () => {
const [, formAction] = useActionState(serverAction, { success: false })

return <Form action={formAction}>
{/* */}
</Form>
}

and consequently I have a server action that processes the payment, and after processing the payment I wanted the user to be redirected to some page depending on the success and I didn't want to have to pass the chargeId to the response
{ success: true, chargeId }
to redirect on the client side
"use server"

export const serverAction = async () => {
  const response = { success: true };

  let chargeId: number | undefined

  after(() => { redirect(`/checkout/${response.success ? "success" : "error"}?chargeId=${chargeId}`) });

  try {
    const charge = checkout({ ... })
    
    chargeId = charge.id;    

    return response;
  } catch (error) {
    response.success = false;
  
    return response;
  }
}

but it's just a matter of preference really
@joulev well you have my answer. after() cannot influence the client so redirect() inside after() doesn't work
Australian Freshwater CrocodileOP
i managed to do what I wanted by using redirect in finally of trycatch, thanks for the reply, joulev
Answer