When building projects with Astro, you can retrieve query parameters in multiple ways, depending on whether you are working on the server or client side. Astro supports SSR (Server-Side Rendering) and the use of standard JavaScript on the client side. Here are two common scenarios:
1. Using Astro's Astro.request Object on the Server Side
Astro's page components allow you to retrieve query parameters on the server side. Each page file can access request information, including query parameters, through the Astro.request object. This is typically used for dynamically generating content during server-side rendering.
Example:
Suppose your website has a page that displays products from different categories based on the query parameter category.
jsx--- // src/pages/products.astro const { searchParams } = new URL(Astro.request.url); // Retrieve the query parameter 'category' const category = searchParams.get('category'); // Dynamically fetch data based on 'category' const products = await fetchProductsByCategory(category); --- <html> <head> <title>Products</title> </head> <body> <h1>Products in Category: {category}</h1> <ul> {products.map(product => ( <li key={product.id}>{product.name}</li> ))} </ul> </body> </html>
In this example, we first create a URL object from Astro.request.url, then use searchParams.get('category') to retrieve the specific query parameter.
2. Using JavaScript on the Client Side
If you need to retrieve query parameters on the client side, you can use standard JavaScript. This is a general method unrelated to Astro, but can be used within pages served by Astro.
Example:
You can directly use JavaScript within the page to retrieve URL query parameters.
html<script> document.addEventListener('DOMContentLoaded', function() { const urlParams = new URLSearchParams(window.location.search); const category = urlParams.get('category'); console.log('Category:', category); }); </script>
This code executes after the document loads, creating a URLSearchParams object to easily access query parameters.
Summary
The choice depends on your specific requirements:
- If you need to dynamically generate page content on the server side based on query parameters, using
Astro.requestis a good choice. - If the query parameters are only used on the client side, or if you need to dynamically read parameters after user interaction, using client-side JavaScript is more appropriate.
In practice, choose the method that best fits your project architecture and user experience needs.