Blog>
Snippets

Basic Search Param Serialization

Demonstrate how to serialize simple key-value pairs into URL search parameters using TanStack Router.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';

// Define your routes
const router = createBrowserRouter([
  {
    path: '/',
    element: '<YourComponent />',
    loader: async ({ params, request }) => {
      // Extract search params
      const url = new URL(request.url);
      const searchParams = Object.fromEntries(url.searchParams);

      // Optional: Serialize search params to use in your component or loader
      console.log(searchParams);

      return { searchParams }; // Return as part of the loader data
    },
  },
]);
Sets up a basic TanStack Router, defining a route that extracts URL search parameters using the loader function. The search parameters are converted from a URLSearchParams object to a plain object for easier use within the component or loader logic.
const queryParams = { name: 'John', age: '30' };

// Convert an object to URLSearchParams to use in navigation
const searchParams = new URLSearchParams(queryParams).toString();

// Use navigate function to change URL with these params
navigate(`/?${searchParams}`);
Demonstrates how to serialize an object containing query parameters into a string suitable for URL search parameters using URLSearchParams. This string can then be appended to the URL path during navigation.