Next.js Discord

Discord Forum

failed to get redirect response TypeError: fetch failed

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
I have the following onSubmit handler:
async function onSubmit(values: z.infer<typeof profileFormSchema>) {
    startTransition(async () => {
      await submitProfile(values)
    })
  }


Where submitProfile is a server action:
export const submitProfile = async (
  profile: z.infer<typeof profileFormSchema>
) => {
  const validatedFields = profileFormSchema.safeParse(profile)
  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
    }
  }
  redirect('/onboarding/job-seeker/experience') //<--- This is what triggers the error
}

While it actually redirects fine, for some reason, the act of redirecting is giving me the following error in the server terminal:
failed to get redirect response TypeError: fetch failed
@useverk/web:dev:     at Object.fetch (node:internal/deps/undici/undici:11372:11)
@useverk/web:dev:     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
@useverk/web:dev:     at async globalThis.fetch (webpack-internal:///(rsc)/../../node_modules/.pnpm/next@14.1.0_@babel+core@7.23.5_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/lib/patch-fetch.js:216:16)
...
truncated for brevity


What might cause this?

67 Replies

@Ray try submit without `startTransition` and see if there is still error ts async function onSubmit(values: z.infer<typeof profileFormSchema>) { await submitProfile(values) }
Giant pandaOP
I thought that might have been it, and I tried that before as well. Doesn't actually change anything
This is the whole error
@Ray ah, try use `router.push()` instead of `redirect`
Giant pandaOP
I'm sure that'll work, I'd just like to handle redirects from the server actions wherever possible :/
because redirect throw a error and it only work if next can catch it
Giant pandaOP
But shouldn't next be able to catch it?
oh submitProfile is a server action?
Giant pandaOP
Yeah
could you show the full code
Giant pandaOP
And the redirection actually happens - The error just shows up in the terminal
export const submitProfile = async (
  profile: z.infer<typeof profileFormSchema>
) => {
  const validatedFields = profileFormSchema.safeParse(profile)
  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
    }
  }
  redirect('/onboarding/job-seeker/experience') //<--- This is what triggers the error
}
This is the full server action
the whole page
Giant pandaOP
This is the form
import { getSession } from '@/lib/auth'
import { isProduction } from '@/lib/env.mjs'
import getUserWithJobseekerProfileByEmail from '@/lib/user/getUserWithJobseekerProfile'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { ProfileForm } from './form'

export default async function RolePage({
  searchParams: { callbackUrl: callbackUrl },
}: {
  searchParams: { callbackUrl: string | null }
}) {
  const session = await getSession()
  const afterSignUpCallbackUrl = encodeURIComponent(
    isProduction
      ? 'https://www.verk.so/onboarding/job-seeker'
      : 'https://localhost:3001/onboarding/job-seeker'
  )

  if (!session) {
    redirect('/login?callbackUrl=' + afterSignUpCallbackUrl)
  }

  const userWithJobProfile = await getUserWithJobseekerProfileByEmail(
    session?.user?.email
  )

  // if (userWithJobProfile.jobSeekerProfile) {
  //   redirect('/profile')
  // }

  if (!userWithJobProfile) {
    redirect('/login?error=notfound')
  }

  const firstName = userWithJobProfile.jobSeekerProfile?.firstName
    ? userWithJobProfile.jobSeekerProfile?.firstName
    : userWithJobProfile.name
    ? userWithJobProfile.name.split(' ')[0]
    : undefined
  const lastName = userWithJobProfile.jobSeekerProfile?.lastName
    ? userWithJobProfile.jobSeekerProfile?.lastName
    : userWithJobProfile.name
    ? userWithJobProfile.name.split(' ')[-1]
    : undefined

  return (
    <div className="flex flex-col gap-4">
      <Link href="/onboarding/role" className="flex w-fit items-center ">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="1.5"
          stroke="currentColor"
          className="w-4 h-4"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"
          />
        </svg>
        <span>Back</span>
      </Link>
      <div>
        <h1 className="text-3xl font-semibold">
          Tell us a little about yourself
        </h1>
      </div>
      <ProfileForm
        bio={userWithJobProfile.jobSeekerProfile?.bio ?? undefined}
        cvUrl={userWithJobProfile.jobSeekerProfile?.cvUrl ?? undefined}
        firstName={firstName}
        lastName={lastName}
        image={userWithJobProfile.image ?? undefined}
        slug={userWithJobProfile.jobSeekerProfile?.slug ?? undefined}
      />
    </div>
  )
}


This is the page
It seems to just be logging the error for some reason
Functionally it works
The redirection happens fine
@Ray because `redirect` throw a error and it only work if next can catch it
Giant pandaOP
So it seems like Next is catching it, but it's still being logged to the console
@Giant panda So it seems like Next is catching it, but it's still being logged to the console
try comment out this
  useEffect(() => {
    if (typeof window !== 'undefined') {
      router.prefetch('/onboarding/job-seeker/experience')
    }
  }, [router])
One more thing it could be related to - I'm using a https certificate on my local development server. So that could be what's causing it
Just haven't had issues with it before
So I don't see why that would be the cause
@Ray `Error: unable to verify the first certificate` yeah sound like that
Giant pandaOP
Doesn't seem to be that. I just did this redirect('/test') on the homepage, and it redirects fine without any issue
could you try without https
is the form on /onboarding/job-seeker/experience?
Giant pandaOP
The form is on /onboarding/job-seeker/profile
Then it should redirect to /onboarding/job-seeker/experience
Give me a sec, I'll see if I can give it a shot without https
Well well well... It happens only on HTTPS
yes because the error is unable to verify the first certificate so it should be related to https
@Ray did you test it on the page or with server action?
Giant pandaOP
Just on the server rendered page
I think it only happen with server action
Giant pandaOP
Most likely, yeah
just ignore it
Giant pandaOP
There's a next experimental-https flag apparently
Maybe I'll try that
oh you were not using experimental-https?
Giant pandaOP
I was doing this:
"dev": "NODE_OPTIONS=--inspect pnpm run with-env next dev & local-ssl-proxy --key ~/certificates/localhost.com+1-key.pem --cert ~/certificates/localhost.com+1.pem --source 3001 --target 3000",
ah
Giant pandaOP
So I manually generated a certificate and setup a hosts file to redirect localhost.com to 127.0.0.1
What a mess
lol
@Ray lol
Giant pandaOP
Actually it seems like the experimental-https wouldn't work for my usecase anyway.

I need to share cookies and sessions across subdomains. And for some reason, that cannot be done on localhost. Must be on something like localhost.com. So I'd still need to point localhost -> localhost.com
So I'll keep running with what I was running, I guess. And then just ignore the redirect errors
@Giant panda Actually it seems like the experimental-https wouldn't work for my usecase anyway. I need to share cookies and sessions across subdomains. And for some reason, that cannot be done on `localhost`. Must be on something like `localhost.com`. So I'd still need to point localhost -> localhost.com
try
"dev": "NODE_OPTIONS=--inspect pnpm run with-env NODE_TLS_REJECT_UNAUTHORIZED=0 next dev & local-ssl-proxy --key ~/certificates/localhost.com+1-key.pem --cert ~/certificates/localhost.com+1.pem --source 3001 --target 3000"
Giant pandaOP
Instacrashed
wait
set env NODE_TLS_REJECT_UNAUTHORIZED to 0
Giant pandaOP
    "dev": "NODE_TLS_REJECT_UNAUTHORIZED=0 NODE_OPTIONS=--inspect pnpm run with-env next dev & local-ssl-proxy --key ~/certificates/localhost.com+1-key.pem --cert ~/certificates/localhost.com+1.pem --source 3001 --target 3000",

Just needed to set the variable in the beginning
yeah try it
Giant pandaOP
❯ pnpm run --filter=web dev

> @useverk/web@ dev /Users/ssardorf/dev/12s12m/verk/apps/web
> NODE_TLS_REJECT_UNAUTHORIZED=0 NODE_OPTIONS=--inspect pnpm run with-env next dev & local-ssl-proxy --key ~/certificates/localhost.com+1-key.pem --cert ~/certificates/localhost.com+1.pem --source 3001 --target 3000

Debugger listening on ws://127.0.0.1:9229/7e44767c-4619-461e-bb91-3cca91d5dd48
For help, see: https://nodejs.org/en/docs/inspector
Started proxy: https://localhost:3001 → http://localhost:3000

> @useverk/web@ with-env /Users/ssardorf/dev/12s12m/verk/apps/web
> dotenv -e ../../.env -- "next" "dev"

Starting inspector on 127.0.0.1:9229 failed: address already in use
Starting inspector on 127.0.0.1:9229 failed: address already in use
Debugger listening on ws://127.0.0.1:9230/e9c3a1e5-1212-4a78-bc37-04cea960ca52
For help, see: https://nodejs.org/en/docs/inspector
   the --inspect option was detected, the Next.js router server should be inspected at port 9230.
   â–² Next.js 14.1.0
   - Local:        http://localhost:3000
   - Environments: .env
   - Experiments (use at your own risk):
     · typedRoutes

(node:84806) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
 ✓ Ready in 2.3s
Try the server action?
yes
it should not verify the cert now
Giant pandaOP
No error!
only use in dev
Giant pandaOP
And this doesn't mess with my ability to share cookies across subdomains, right?
yes it shouldn't affect it
just skip verify the cert
Giant pandaOP
Amazing, thanks a lot!
no prob