Next.js Discord

Discord Forum

Server action throws an error sometimes

Unanswered
Florida White posted this in #help-forum
Open in Discord
Avatar
Florida WhiteOP
Hey, I have a small application with public forms. Example structure of per form is page.tsx (server-component with using serverAction to fetch dictionaries or other required data) and form.tsx with form which is used in page.tsx. I also have middleware with authentication which uses our own AuthService. When I'm using multiple tabs to test it, sometimes server actions are failing because of missing token so there is propably some race conditional problem. I'm checking auth in middleware and then receiving it from headers() in server action and passing to endpoint in our API (which is external). Did you faced something like that?

5 Replies

Avatar
Florida WhiteOP
Let me put my files here:
Image
Image
example server action
export async function getCaseTypes(lng: string = LANGUAGES.ENGLISH): Promise<CaseTypesDictionary> {
  noStore();
  try {
    const response = await fetch(`${getServiceUrl(process.env.BASE_API_PATH)}/online-forms/dictionary/caseTypes`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: headers().get("Authorization")!
      }
    });

    if (!response.ok) {
      throw new Error("Failed to fetch case types dictionary");
    }

    let responseData: CaseTypesDictionaryResponse = await response.json();
    if (lng.toLocaleLowerCase() === LANGUAGES.IRISH) {
      responseData = responseData.map((x) => ({ ...x, name: x.irishName || x.name }));
    }
    return responseData;
  } catch (error) {
    return HttpParseError({ error: error as RequestError });
  }
}
and page.tsx
export default async function ConsumerContact({ params: { lng } }: Params<{ lng: string }>) {
  const { t } = await useTranslation(lng);

  const caseTypes = await getCaseTypes(lng);
  const categories = await getCategories(lng);
  return (
    <Container>
      <Heading boxProps={{ textAlign: "center" }} sxProps={{ paddingY: 3 }}>
        <Typography sx={{ fontSize: "1.5rem" }} component={"h1"}>
          {t(`${CONSUMER_CONTACT_FORM}.Title`)}
        </Typography>
      </Heading>
      <Typography component={"p"} my={1}>
        {t(`${CONSUMER_CONTACT_FORM}.Description.one`)}
      </Typography>
      <Typography component={"p"} my={1}>
        <Trans
          i18nKey={`${CONSUMER_CONTACT_FORM}.Description.two`}
          components={[
            <Link
              sx={{ textDecoration: "underline", color: "primary" }}
              href="https://www.nationaltransport.ie/further-information/privacy-statement/"
              target="_blank"
              rel="noreferrer"
            />
          ]}
        ></Trans>
      </Typography>
      <Typography component={"p"} my={1}>
        <Trans
          i18nKey={`${CONSUMER_CONTACT_FORM}.Description.three`}
          components={[
            <Link
              sx={{ textDecoration: "underline", color: "primary" }}
              href={`/${lng}/consumer-complaint`}
              target="_blank"
              rel="noreferrer"
            />,
            <Link
              sx={{ textDecoration: "underline", color: "primary" }}
              href={`/${lng}/spsv-contact-form`}
              target="_blank"
              rel="noreferrer"
            />
          ]}
        ></Trans>
      </Typography>
      <GoogleCaptchaWrapper recaptchaKey={process.env.RECAPTCHA_SITE_KEY}>
        <ConsumerContactForm caseTypes={caseTypes} categories={categories} />
      </GoogleCaptchaWrapper>
    </Container>
  );
}