npm package: @rtd/use-suggestions
Description: 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.
Author: Peter Washington
Latest version: 2.2.0

# 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:

```bash
yarn add @rtd/use-suggestions
```

or

```bash
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):_

```typescript
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):_

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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.

```typescript
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.

```typescript
/**
 * 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.

```typescript
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:

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

Solution: Follow the [Setup](#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:

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

The hook throws a validation error:

```bash
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:

```bash
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.