Next.js Discord

Discord Forum

Redirect in Actions Server

Unanswered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
I am trying to redirect to another page after making a post request using server actions, as follows:

export async function asingDocente(formData) {
  try {
    const data = {
      idDocente: formData.get('idDocente'),
      idEvaluacionAsignatura: formData.get('idEvaluacionAsignatura'),
    };

    asignDocenteSchema.parse(data);

    const payload = {
      idDocente: data.idDocente,
    };

    const url = COORDINACION_ACADEMICA.PUT_RELACION_DOCENTE_ASIGNATURA(data.idEvaluacionAsignatura);

    await fetchPut(url, payload);

    revalidatePath('/dashboard/ca-admin-docente-asignatura');
    redirect('/dashboard/ca-admin-docente-asignatura'); // The error occurs on this line
  } catch (error) {
    console.error('Error occurred:', error);

    if (error instanceof z.ZodError) {
      return { message: 'Datos inválidos', errors: error.errors };
    }

    return { message: 'Ocurrió algún error' };
  }
}


Error occurred: Error: NEXT_REDIRECT
    at getRedirectError (webpack-internal:///(rsc)/./node_modules/next/dist/client/components/redirect.js:49:19)
    at redirect (webpack-internal:///(rsc)/./node_modules/next/dist/client/components/redirect.js:60:11)
    at asingDocente (webpack-internal:///(rsc)/./src/app/lib/actions/ca/ca-admin-docente-asignatura.js:62:66)

 digest: 'NEXT_REDIRECT;replace;/dashboard/ca-admin-docente-asignatura;303;',
  mutableCookies: p {
    _parsed: Map(1) { 'Studio-e32749e7' => [Object] },
    _headers: HeadersList {
      cookies: [Array],
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    }
  }
}



I don't quite understand why this happens, but the pat data is revalidated. And I also don't know the correct way to show a toast to the user to let them know if the change was made or not.

Could someone guide me, I'm new to learning Next.

4 Replies

Velvet ant
dont use redirect inside a try/catch block
redirect internally throws an error so it should be called outside of try/catch blocks.
Alligator mississippiensisOP
Okey, thanks @Velvet ant