I'm unable to access the query parameters of an astro file.
Given the url http://localhost:3000/example?hello=meow
:
How can I access {hello: "meow"}
from within the example.astro
file?
I'm unable to access the query parameters of an astro file.
Given the url http://localhost:3000/example?hello=meow
:
How can I access {hello: "meow"}
from within the example.astro
file?
- Does this answer your question? How to get the querystring parameters with Astro – BadPiggie Commented Aug 17, 2022 at 4:53
- @BadPiggie nope this is specifically using the query params on the client / front-end js. – ThomasReggi Commented Aug 17, 2022 at 14:50
-
What do you mean by
server side
. The pages inAstro
are rendered up-front and are entirely static – BadPiggie Commented Aug 17, 2022 at 15:38 -
@BadPiggie there's a
output: "server"
mode where it does ssr instead. – ThomasReggi Commented Aug 17, 2022 at 17:55
1 Answer
Reset to default 9If you're writing an API route, then you'd use a .ts
or .js
file [source].
In that, you can write a get
method like this:
export async function get({request}) {
// process the URL into a more usable format
const url = new URL(request.url)
const params = new URLSearchParams(url.search)
// set up a response object
const data = {
hello: params.get('hello'),
};
// this will yield { hello: 'meow' } on your Astro server console
console.log(data)
// return the response
return new Response(JSON.stringify(data), {
status: 200
}); }
From an .astro
file you can access the url through const { url } = Astro.request;
for SSR, I think. For static pages, you can do it through const url = Astro.url;
[source].