DEV Community

Turing
Turing

Posted on

5 Nextjs API Query Params Examples

API query parameters are key-value pairs that are appended to the URL of an API request to send additional information to the server. They allow clients (such as web browsers or applications) to specify certain criteria or pass data when making a request to the server.

Query parameters are added to the end of the URL after a question mark (?). Each parameter is a key-value pair, with the key and value separated by an equals sign (=). If there are multiple query parameters, they are separated by an ampersand (&).

How Query Parameters Are Used:
Filtering Data: Clients can use query parameters to filter the data they want. For example, ?category=books might tell the server to only return items from the "books" category.

Pagination: Query parameters are often used for pagination in API requests, allowing the client to specify which page of results to fetch and how many items per page. Example: ?page=2&limit=10.

Sorting and Ordering: Query parameters can be used to specify how data should be sorted. For example, ?sort=price&order=asc could instruct the server to return items sorted by price in ascending order.

Passing Search Terms: APIs often use query parameters to allow clients to search for data. For instance, ?search=laptop might be used to find all products that match the term "laptop."

Query parameters are highly flexible and can be used in various ways, depending on how the API is designed. They allow for dynamic interaction between the client and server, making it easier to request customized data.

  1. Basic Query Parameter Handling This API handler demonstrates how to extract and use query parameters to return a personalized greeting.
// pages/api/greet.js

export default function handler(req, res) {
  const { name } = req.query; // Get the 'name' query parameter
  const greeting = name ? `Hello, ${name}!` : 'Hello, stranger!';

  res.status(200).json({ message: greeting });
}

Enter fullscreen mode Exit fullscreen mode

Example usage:
/api/greet?name=John will return { "message": "Hello, John!" }
/api/greet will return { "message": "Hello, stranger!" }

  1. Multiple Query Parameters In this example, the API handler extracts multiple query parameters to return a formatted response based on user inputs.

// pages/api/user.js

export default function handler(req, res) {
  const { name, age } = req.query; // Get 'name' and 'age' query parameters

  if (!name || !age) {
    res.status(400).json({ error: 'Name and age are required' });
    return;
  }

  res.status(200).json({ message: `User ${name} is ${age} years old.` });
}
Enter fullscreen mode Exit fullscreen mode

Example usage:
/api/user?name=Jane&age=28 will return { "message": "User Jane is 28 years old." }
/api/user?name=Jane will return { "error": "Name and age are required" }

  1. Optional Query Parameters with Default Values This example shows how to handle optional query parameters by providing default values when parameters are missing.
// pages/api/score.js

export default function handler(req, res) {
  const { player = 'Anonymous', score = '0' } = req.query; // Default values if missing

  res.status(200).json({ message: `${player} scored ${score} points!` });
}
Enter fullscreen mode Exit fullscreen mode

Example usage:
/api/score?player=Alex&score=100 will return { "message": "Alex scored 100 points!" }
/api/score will return { "message": "Anonymous scored 0 points!" }

  1. Handling Arrays in Query Parameters Next.js allows query parameters to be passed as arrays. This example demonstrates how to handle an array of values.
// pages/api/tags.js

export default function handler(req, res) {
  const { tags } = req.query; // Get 'tags' query parameter (array)

  if (!tags) {
    res.status(400).json({ error: 'Tags are required' });
    return;
  }

  res.status(200).json({ message: `You have selected these tags: ${tags.join(', ')}` });
}
Enter fullscreen mode Exit fullscreen mode

Example usage:
/api/tags?tags=javascript&tags=react will return { "message": "You have selected these tags: javascript, react" }
/api/tags will return { "error": "Tags are required" }

  1. Pagination with Query Parameters This handler demonstrates how to implement pagination using query parameters for page and limit.

// pages/api/items.js

export default function handler(req, res) {
  const { page = 1, limit = 10 } = req.query; // Default values for page and limit
  const startIndex = (page - 1) * limit;
  const endIndex = startIndex + Number(limit);

  // Dummy data for demonstration
  const items = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
  const paginatedItems = items.slice(startIndex, endIndex);

  res.status(200).json({
    currentPage: page,
    perPage: limit,
    items: paginatedItems,
  });
}
Enter fullscreen mode Exit fullscreen mode

Example usage:
/api/items?page=2&limit=5 will return the next 5 items, such as { "items": ["Item 6", "Item 7", "Item 8", "Item 9", "Item 10"] }
/api/items (default values) will return the first 10 items, such as { "items": ["Item 1", "Item 2", ..., "Item 10"] }

These examples demonstrate the flexibility of using query parameters in Next.js API routes, covering common patterns like single or multiple parameters, optional values, arrays, and pagination.

Top comments (0)