Next.js Discord

Discord Forum

Are absolute URLs required when calling `redirect` from a server action?

Unanswered
charlton posted this in #help-forum
Open in Discord
I'm using the following server action, triggered by a form submission. I'm using an absolute path, but am not including the hostname, etc.

  // Server Action
  async function accept(formData: FormData) {
    'use server'
    
    // do some stuff
    const projectId = await doSomeStuff()
    const redirectTo = `/alpha/project/${projectId}`
    redirect(redirectTo)
  }


But the redirect never happens, and I get the following error. I have verified that projectId is valid.
- error Error [TypeError]: Invalid URL
    at new NodeError (node:internal/errors:399:5)
    at new URL (node:internal/url:560:13)
    at parseURL (webpack-internal:///(ssr)/./node_modules/.pnpm/next@13.4.19_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/esm/server/web/next-url.js:15:12)
    at new NextURL (webpack-internal:///(ssr)/./node_modules/.pnpm/next@13.4.19_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/esm/server/web/next-url.js:29:18)
    at adapter (webpack-internal:///(ssr)/./node_modules/.pnpm/next@13.4.19_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/esm/server/web/adapter.js:201:28)
   ...


When I replace the path with a full URL (e.g. http://localhost:300/alpha/...), everything works fine. But ideally the server action wouldn't need to know information about the host, etc. Are absolute URLs required? I'm not seeing anything in the docs about this.

4 Replies

Redirect in general requires a absolute url
If i remember correctly
Hmm, that hasn't been my experience. I've used relative redirects in plenty of places. The docs say both are permitted. https://nextjs.org/docs/app/api-reference/functions/redirect
Ah, my wording in the post title is off. I mean absolute URL, with the hostname. Not just the path. I'm using an absolute path.