npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rtd/use-suggestions

v2.2.0

Published

A React hook for fetching search suggestions securely through a Next.js proxy. This package includes a custom hook, helper functions for creating proxy routes, types, and constants to simplify integration with your React/TypeScript projects.

Downloads

216

Readme

use-suggestions

A React hook for fetching search suggestions securely through a Next.js proxy. This package includes a custom hook, helper functions for creating proxy routes, types, and constants to simplify integration with your React/TypeScript projects.

Note: The createSuggestionsProxyHandler helper is now deprecated as of v2.2.0. Please use the new forwardProxyRequest utility for creating your proxy routes. In addition to the suggestions endpoint, you can now also target the retrieval endpoint (used, for example, to complete partial location data).

Installation

You can install the package using Yarn or npm:

yarn add @rtd/use-suggestions

or

npm install @rtd/use-suggestions

Setup

Create the Proxy Route in Next.js

To protect your API key, you must create a Next.js API route that acts as a proxy to the external API. Use the new forwardProxyRequest utility (import it from @rtd/use-suggestions/server for server-only code).

The utility accepts a configuration object of type ProxyHandlerConfig, which now includes an endpoint property. Use: • endpoint: 'suggest' – to forward requests to the suggestions endpoint • endpoint: 'retrieve' – to forward requests to the lookup/retrieve endpoint

For Next.js 12 (pages/api/suggestions.ts):

import type { NextApiRequest, NextApiResponse } from 'next'
import {
  forwardProxyRequest,
  ProxyHandlerConfig,
  GenericRequest,
} from '@rtd/use-suggestions/server'

const config: ProxyHandlerConfig = {
  apiKey: process.env.API_KEY || '',
  baseUrl: 'https://api.suggestions.com/endpoint',
  // Use 'suggest' to forward to "/api/v1/suggestions"
  // or 'retrieve' to forward to "/api/v1/lookup/retrieve"
  endpoint: 'suggest',
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // Create a GenericRequest; req.url includes any query parameters.
  const genericRequest: GenericRequest = {
    originalUrl: req.url,
  }

  try {
    const { status, data } = await forwardProxyRequest(genericRequest, config)
    res.status(status).json(data)
  } catch (error: any) {
    console.error('Proxy error:', error)
    res.status(500).json({ error: error.message || 'Internal Server Error' })
  }
}

For Next.js 13 (app/api/suggestions/route.ts):

import { NextResponse } from 'next/server'
import {
  forwardProxyRequest,
  ProxyHandlerConfig,
  GenericRequest,
} from '@rtd/use-suggestions/server'

const config: ProxyHandlerConfig = {
  apiKey: process.env.API_KEY || '',
  baseUrl: 'https://api.suggestions.com/endpoint',
  endpoint: 'suggest', // or 'retrieve' for the retrieval endpoint
}

export async function GET(request: Request) {
  // Create a URL object to extract the query string.
  const url = new URL(request.url)
  const genericRequest: GenericRequest = {
    originalUrl: url.search, // Only the query string (e.g., "?q=term&foo=bar")
  }

  try {
    const { status, data } = await forwardProxyRequest(genericRequest, config)
    return NextResponse.json(data, { status })
  } catch (error: any) {
    console.error('Proxy error:', error)
    return NextResponse.json(
      { error: error.message || 'Internal Server Error' },
      { status: 500 }
    )
  }
}

Usage

Using the Retrieve Endpoint

If you need to complete partial suggestion data (for example, when locations return with null coordinates), you can target the retrieve endpoint by setting the endpoint value in your configuration:

const config: ProxyHandlerConfig = {
  apiKey: process.env.API_KEY || '',
  baseUrl: 'https://api.suggestions.com/endpoint',
  endpoint: 'retrieve', // This will forward to "/api/v1/lookup/retrieve"
}

Usage in React

Importing the Hook

Import the useSuggestions hook, types, and constants in your React component:

import React, { useState } from 'react'
import useSuggestions, { SuggestionsOptions } from '@rtd/use-suggestions'

Example Component

Here’s an example of how to use the useSuggestions hook in a React component:

const SuggestionComponent: React.FC = () => {
  const [query, setQuery] = useState('')

  const options: SuggestionsOptions = {
    includeStops: true,
    includeConcerts: true,
    location: { lat: 39.7392, lng: -104.9903 },
    debounceTime: 400,
  }

  const { suggestions, isLoading, error } = useSuggestions(query, options)

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search for suggestions"
      />
      {isLoading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      <ul>
        {suggestions.map((suggestion) => (
          <li key={suggestion.slug}>{suggestion.name}</li>
        ))}
      </ul>
    </div>
  )
}

export default SuggestionComponent

Hook API

useSuggestions

Fetches search suggestions from the API.

Parameters:

  • rawQuery: string - The search query string.
  • options: SuggestionsOptions - Configuration options for the suggestions.
  • proxyPath?: string - (Optional) Relative path to the proxy route. Defaults to /api/suggestions.

Returns:

  • suggestions: SearchableSuggestion[] - An array of suggestions.
  • isLoading: boolean - Loading state.
  • error: Error | null - Error state.

Types

The package includes several types to help with type safety in your project:

SuggestionsOptions

Configuration options for the suggestions.

interface SuggestionsOptions {
  includeStops?: boolean
  includeRoutes?: boolean
  includeLocations?: boolean
  includeDestinations?: boolean
  includeConcerts?: boolean
  location?: {
    lat: number
    lng: number
  }
  debounceTime?: number
}

SearchableSuggestion

Base interface for a searchable suggestion.

/**
 * Suggestion Types Returned by the Server
 */
export type SuggestionType =
  | 'location'
  | 'concert'
  | 'stop'
  | 'station'
  | 'route'
  | 'destination'

/**
 * Point Coordinates
 */
export interface Point {
  lat: number
  lng: number
}

/**
 * Base Suggestion with Common Fields
 */
export interface BaseSuggestion extends Point {
  suggestionType: SuggestionType
  name: string
  label: string
  slug: string
  score: number
}

Constants

The package includes the following constants:

DEBOUNCE_TIME_IN_MS

Default debounce time for the search query.

export const DEBOUNCE_TIME_IN_MS = 432

Common Errors

1. Proxy Route Not Configured

If you attempt to use the hook without first creating a proxy route, you will see the following error:

Proxy route not found: "/api/suggestions".
Ensure the proxy route exists and is set up using the 'forwardProxyRequest' utility.

Solution: Follow the Setup section to create the API route.

2. Invalid Proxy Path

If a developer attempts to pass an external API URL instead of a relative path to the hook:

useSuggestions('query', options, 'https://api.suggestions.com');

The hook throws a validation error:

Invalid proxyPath: "https://api.suggestions.com".
The proxyPath must be a relative path starting with "/".

Solution: Use a relative path, such as /api/suggestions.

Building the Package

To build the package, run:

yarn build

This will compile the TypeScript files and output the results in the dist directory.

License

This project is licensed under the MIT License.