Next.js Discord

Discord Forum

How to get URL searchParams in form ServerAction?

Answered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
A user can login at this url /sign-in?redirect=%2Fdashboard%3F and I'm trying to read the searchParams in the Server Action, but I can't see how. Is there an event argument or something I can use to see the url the request is coming from?
Answered by Ray
I think you could try to read it from the props of the page component or use useSearchParams() hook in client component then pass to the action
View full answer

7 Replies

Masai LionOP
Doing it like this. Seems like a round about way of doing it, but it works.

  // some ServerAction function
  const _headers = headers();
  const referrer = _headers.get("referer") as string;
  const url = new URL(referrer);
  let redirectPath = url.searchParams.get("redirect");
  if (redirectPath) {
    redirectPath = decodeURIComponent(redirectPath);
  } else {
    redirectPath = "/dashboard";
  }
  return redirect(redirectPath);
Answer
Masai LionOP
How to pass it? In a hidden input in the form?
Masai LionOP
Does bind work with useFormState hook? Then my server action would have 3 arguments? someAction(initialFormState, bindValue, formData);)
@Masai Lion Does bind work with `useFormState` hook? Then my server action would have 3 arguments? `someAction(initialFormState, bindValue, formData);`)
yes
const [state, formAction] = useFormState(action.bind(null, searchParams), initialState)

then in your action
export async function action(searchParams, prevState, formData) {}
Masai LionOP
Thanks for your input!