İçeriğe geç

querystring with Astro

What is a Querystring?

A querystring is a string that specifies the parameters of a URL. The querystring starts after the ? character at the end of the URL and the parameters are separated by the & character. Each parameter is a key-value pair separated by the = character.

For example, in the URL https://example.com/?name=John&age=30, there are two parameters named name and age. The value of the name parameter is John, and the value of the age parameter is 30.

Requirements for Querystring in Astro

In Astro, SSR (Server-Side Rendering) is used for querystrings. SSR is a JavaScript process that runs on the server when a page is loaded. This process generates the content of the page and sends it to the browser. SSR can use the parameters in the querystring to generate the content of the page.

To enable this, add this page to your current project and set output:server or output:hybrid in the astro.config.mjs file.

Using Querystring with Astro

In Astro, we will create a middleware to use querystring. To create this middleware, create a file named middleware.ts in the src/ folder of Astro and add the following code:

import { defineMiddleware } from "astro/middleware";
export const onRequest = defineMiddleware((context, next) => {
let query = new URLSearchParams(context.url.search);
context.locals.page = Number(query.get('page')) || 1;
return next();

In this code, we use the URLSearchParams class to get the querystring in the URL. This class is used to get and process the querystring in the URL. We can get the values of the parameters in the querystring using the get method. If the parameter is not found, it returns null. So we convert the value to a number using the Number function. If the parameter is not found or the value cannot be converted to a number, we set the page number to 1.

We will start getting type errors when we send data to context.locals.page, so let’s add the following code to the env.d.ts file:

declare App {
interface Locals {
page: number;
}
}

With these codes, we have determined the type of the data that will come into the page.

Then we can go to our page and use the page variable.

---
console.log("page",Astro.locals.page);
---

We can print the page data to the console in this way.

Page Numbering with Querystring

For example, let’s say we want to paginate a blog page. We can use the querystring for pagination. For example, in the URL https://example.com/blog?page=2, we can set the page number with the page parameter.

---
let page = Astro.locals.page;
---
<div>
<h1>Blog</h1>
<p>page: {page}</p>
</div>

In this example, we get the page number with the Astro.locals.page variable and print the page number on the screen.

More Information

For more information, you can refer to the Astro Middleware documentation.