Search code examples
javascriptreactjshttp-redirectnext.jsnextjs14

redirect function in nextjs 14 takes too long


I have a problem in the redirect function in next.js 14 the problem is that the redirect process takes about 5 minutes , and this happens only on the server . I have a VPS on namecheap with WHM and Cpanel and I am running the application on the appache server using passenger .

the thing that is disturbing me is that this problem didn't appear for about 3 months but suddenly it happened , in addition to that it just on the server build (when I build on my device and try to run it it works and the redirect happens immediatly) .

I am using pwa and I got suspicion in it so I removed it and still the same .

"use client";
    const Login = ({ url, pageType }: { url: string; pageType: string }) => {
        const handleSubmit = (data: { email: string; password: string }) => {
            setError(false);
            return POST<AuthResponse>(url, data).then((res: any) => {
              if (res.code == 401) {
                setError(true);
                return res;
              } else {
                return res;
              }
            });
          };
        const handleSuccess = (data: ApiResponse<AuthResponse>) => {
            setCookieClient("token", data?.data?.token ?? "");
            setCookieClient("refresh_token", data?.data?.refresh_token ?? "");
            setCookieClient("user-type", pageType);
            Navigate("/admin");
          };
        <Form
                  handleSubmit={handleSubmit}
                  onSuccess={handleSuccess}
                  buttonText={"Login"}
                >
            {/*from fields*/}
        
        </Form>

the Navigate action :

"use server";
import { redirect } from "next/navigation";

export async function Navigate(url: string) {
  redirect(url)
}

the form component :

"use client";
import React from "react";
import { FormProvider, useForm } from "react-hook-form";
import { ApiResponse } from "@/Http/Response";
import LoadingSpin from "@/components/icons/LoadingSpin";
import PrimaryButton from "./PrimaryButton";
import { toast } from "react-toastify";

const Form = ({
  children,
  handleSubmit,
  onSuccess,
  defaultValues = {},
  buttonText = "Submit",
}: {
  children: React.ReactNode;
  handleSubmit: (data: any) => Promise<ApiResponse<any>>;
  defaultValues?: object | undefined | null;
  onSuccess?: (res: ApiResponse<any>) => void;
  buttonText?: string;
}) => {
  // @ts-ignore
  const methods = useForm({ defaultValues: defaultValues });

  const onSubmit = async (data: any) => {
    const res = await handleSubmit(data);

    if (!res.hasValidationErrors() && res.code == 200) {
      toast.success((res?.message as string) ?? "success");
      if (onSuccess) onSuccess(res);
    } else {
      res.fillValidationErrors(methods);
    }
    return res;
  };

  return (
    <FormProvider {...methods}>
      <form
        onSubmit={methods.handleSubmit(onSubmit)}
        encType="multipart/form-data"
      >
        {children}
        <div
          className="flex justify-center items-center my-5"
          onClick={() => {
            methods.clearErrors();
          }}
        >
          <PrimaryButton
            type="submit"
            disabled={methods.formState.isSubmitting}
          >
            {buttonText}{" "}
            {methods.formState.isSubmitting ? (
              <span className="mx-1">
                <LoadingSpin className="w-6 h-6 text-white" />
              </span>
            ) : (
              ""
            )}
          </PrimaryButton>
        </div>
      </form>
    </FormProvider>
  );
};

export default Form;

Solution

  • I solve it .

    the problem was in the apache module (passenger) it wasn't redirect requests immediately (didn't know what is the problem with it for sure but I think it is in its reverse proxy)

    so instead of using passenger I used pm2 and added a virtual machine config to my domain to redirect all requests of the domain to the node.js server using this config :

    ServerName www.example.com
    
      ProxyRequests off
      ProxyPass / http://127.0.0.1:3000/
      ProxyPassReverse / http://127.0.0.1:3000/
      
      <Proxy *>
        Require all granted
      </Proxy>
    
      ErrorLog /var/log/apache2/www.example.com-error_log
      CustomLog /var/log/apache2/www.example.com-access_log common