Next.js Discord

Discord Forum

Server component metadata crashing an error

Unanswered
Loïs posted this in #help-forum
Open in Discord
I have a NextJS 14.0.1 using node 21.1.0

I have an empty edit user page with just a button in a card (button is a client component)
In this case everything is okay (page render successfully and metadatas are present):
./app/(protected)/(dashboard)\users\[username]\edit\page.tsx
export const generateMetadata = async ({ params }: { params: UserEditPageParams}): Promise<Metadata> => {
  return {
    title: `Éditer l'utilisateur ${params.username}`,
  }
}

type UserEditPageParams = {
  username: string;
}
export default async function UserEditPage({ params }: { params: UserEditPageParams}) {
  [...]

  if (!usersEditPermission) {
    return (
      <div>Unauthorized</div>
    )
  }

  if (!targetUser) {
    return (
      <div>Not found</div>
    )
  }

  if (usersEditGroupPermissions) {
    groups = await GroupAPI.getAll(token);
  }

  return (
    <div className='flex flex-col items-center'>
      <Title className='w-full max-w-xl'>Éditer l'utilisateur</Title>

      <div className='w-full max-w-xl space-y-4'>
        <Card className='space-y-2'>
          <Avatar size={'lg'} shape='rounded' user={targetUser} />
          <h2 className='text-xl font-bold'>{targetUser.full_name}</h2>
        </Card>

        <Card>
          <Title>Informations générales</Title>

          <Button>
            I'm a client component
          </Button>
        </Card>
      </div>
    </div>
  )
}


But now when i add my edit general informations form somewhere in the page (which is also a client component like my button 👀) the page crash with the error:
type EditUserGeneralInformationsFormProps = {
  user: UserDTO;
}
export default function EditUserGeneralInformationsForm({ user }: EditUserGeneralInformationsFormProps) {
  const { data: session } = useSession();
  const router = useRouter();

  const {
    register,
    handleSubmit,
    formState: {
      errors,
      isSubmitting,
      isDirty
    },
    reset
  } = useForm<TEditUserGeneralInformationsSchema>({
    resolver: zodResolver(EditUserGeneralInformationsSchema),
    defaultValues: user
  });

  const onSubmit = async (data: TEditUserGeneralInformationsSchema) => {
    const updateResponse: UpdateUserResponseDTO = await UserAPI.update(user.id, data, getTokenFromSession(session)).catch(toastError);

    if (!updateResponse)
      return;

    if (!updateResponse.success) {
      toast.error(updateResponse.messages);
      return;
    }

    if (updateResponse.user.username !== user.username) {
      router.replace(USER_EDIT_PAGE_URL.replace('[username]', updateResponse.user.username));                           /*   THIS LINE SEEMS TO BE THE PROBLEM           */
    }

    reset(updateResponse.user);
    toast.success('Informations générales mises à jour avec succès');
  }

  return (
    <Form handleSubmit={handleSubmit(onSubmit)}>
      <Input type='text' title="Nom d'utilisateur" name='username' register={register} errors={errors} />
      <Input type='text' title="Prénom" name='first_name' register={register} errors={errors} />
      <Input type='text' title="Nom de famille" name='last_name' register={register} errors={errors} />
      <Input type='text' title="Adresse email" name='email' register={register} errors={errors} />

      <Button type='submit' disabled={ !isDirty || isSubmitting }>
        Sauvegarder
      </Button>
    </Form>
  )
}


After digging, when i remove this line the page now works successully
router.replace(USER_EDIT_PAGE_URL.replace('[username]', updateResponse.user.username));


I use this import:
import { useRouter } from 'next/navigation';


I don't have any idea to fix that problem
Thx for the help

1 Reply

After digging a little bit more it seems to not be router.replace but the exported variable used in the router.replace causing the issue
router.replacer('/random/url');

✅

but with the exported variable in the page.tsx :
router.replace(USER_EDIT_PAGE_URL);

❌

Variable in page.tsx:
export const USER_EDIT_PAGE_URL = '/users/[username]/edit'


Should i put all theses url variables in a single dedicated file ?