Access pathname in server action
Answered
Pigeon tremex posted this in #help-forum
Pigeon tremexOP
I'd like to know the hostname and/or the current pathname (or even better the whole request object) in an server action. Is there an option how I can access those? I can use the headers, extract the root URL from there, but it's a bit tiresome in comparison to the usage of the request/response objects.
From the headers I can get the
From the headers I can get the
origin and the referrer (referer))Answered by joulev
Nope you can’t. The best you can do is
1. (recommended) pass the pathname along with relevant information as a server action function argument
2. Use headers() as you are doing.
1. (recommended) pass the pathname along with relevant information as a server action function argument
2. Use headers() as you are doing.
8 Replies
@Pigeon tremex I'd like to know the hostname and/or the current pathname (or even better the whole request object) in an server action. Is there an option how I can access those? I can use the headers, extract the root URL from there, but it's a bit tiresome in comparison to the usage of the request/response objects.
From the headers I can get the `origin` and the `referrer` (referer))
Nope you can’t. The best you can do is
1. (recommended) pass the pathname along with relevant information as a server action function argument
2. Use headers() as you are doing.
1. (recommended) pass the pathname along with relevant information as a server action function argument
2. Use headers() as you are doing.
Answer
Pigeon tremexOP
server action function argument
To 1. - and with https://react.dev/reference/react/useActionState#useactionstate (?)
Sth like this?
async function increment(previousState, formData) {
return previousState + 1;
}
- const [state, formAction] = useActionState(increment, 0);
+ const [state, formAction] = useActionState((payload) => increment(payload, "my-path"), 0);And the third argument of increment will be my extra argument ("my-path")?
American Crow
I think joulev is talking about binding additional arguments to server actions
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#passing-additional-arguments
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#passing-additional-arguments
Pigeon tremexOP
Ah, I forgot about that, thank you! For sake of simplicity, I went with a hidden input for now
To be honst, I have no idea how I mark this post as "solved"
/solved
American Crow
Rightclick on jouldev answer -> apps -> solved somth like that
👍