### Install with npm
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Install the package using npm.
```bash
npm install @hiprax/use-seo
```
--------------------------------
### Install with yarn
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Install the package using yarn.
```bash
yarn add @hiprax/use-seo
```
--------------------------------
### Install with pnpm
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Install the package using pnpm.
```bash
pnpm add @hiprax/use-seo
```
--------------------------------
### validateDescriptionLength example
Source: https://github.com/hiprax/use-seo
Example call showing warning message for short description.
```TypeScript
validateDescriptionLength('Short description');
// ['Description is 17 characters. Consider 120-160 characters for better SEO.']
```
--------------------------------
### validateKeywordsCount example
Source: https://github.com/hiprax/use-seo
Example call showing warning message when keyword count exceeds the maximum.
```TypeScript
validateKeywordsCount('a,b,c,d,e,f,g,h,i,j,k,l');
// ['Too many keywords (12). Focus on 10 or fewer relevant keywords.']
```
--------------------------------
### createJsonLdScript usage example
Source: https://github.com/hiprax/use-seo
Example of calling createJsonLdScript with a structured-data object and appending the returned script to document.head if it is not null.
```TypeScript
const script = createJsonLdScript(
{
'@context': 'https://schema.org',
'@type': 'Article',
headline: 'Article Title',
},
0
);
if (script) {
document.head.appendChild(script);
}
```
--------------------------------
### Profile and Book OG types with additionalMetaTags
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Use property namespacing for OG profile and book metadata. The profile example sets first_name, last_name, username, and gender; the book example sets author, isbn, release_date, and tag. Both delegate to additionalMetaTags.
```tsx
useSEO({
ogType: 'profile',
additionalMetaTags: [
{ property: 'profile:first_name', content: 'Jane' },
{ property: 'profile:last_name', content: 'Doe' },
{ property: 'profile:username', content: 'janedoe' },
{ property: 'profile:gender', content: 'female' },
],
});
useSEO({
ogType: 'book',
additionalMetaTags: [
{ property: 'book:author', content: 'https://example.com/authors/jane' },
{ property: 'book:isbn', content: '978-3-16-148410-0' },
{ property: 'book:release_date', content: '2024-03-15' },
{ property: 'book:tag', content: 'fiction' },
],
});
```
--------------------------------
### validateTitleLength examples
Source: https://github.com/hiprax/use-seo
Example calls showing warning message for short titles and empty array for valid length.
```TypeScript
validateTitleLength('Short');
// ['Title is 5 characters. Consider 30-60 characters for better descriptiveness.']
```
```TypeScript
validateTitleLength('A title that is between 30 and 60 characters long');
// []
```
--------------------------------
### createMeta usage example
Source: https://github.com/hiprax/use-seo
Creates a meta element for og:image and sets its content attribute.
```TypeScript
const meta = createMeta({ property: 'og:image' });
meta.setAttribute('content', 'https://example.com/image.jpg');
```
--------------------------------
### useSEO top-level usage example
Source: https://github.com/hiprax/use-seo
Example of using the useSEO hook in a React component. It sets the page title, description, and Open Graph image. The hook is called at the top level of the component.
```TSX
import { useSEO } from 'use-seo';
function MyPage() {
useSEO({
title: 'My Amazing Page',
description: 'This is the best page ever',
ogImage: 'https://example.com/og.jpg',
});
return
Content
;
}
```
--------------------------------
### shouldEnableWarnings usage example
Source: https://github.com/hiprax/use-seo
Example of calling shouldEnableWarnings to get a boolean indicating development mode. Returns true in dev, false in prod.
```ts
import { shouldEnableWarnings } from '@hiprax/use-seo/utils';
const warnEnabled = shouldEnableWarnings(); // true in dev, false in prod
```
--------------------------------
### formatTitle usage examples
Source: https://github.com/hiprax/use-seo
Shows how to call formatTitle with different options: template with %s placeholder, suffix, prefix, both prefix and suffix, and template with {title} placeholder. The template is substituted literally via split/join to avoid replacement semantics.
```ts
import { formatTitle } from '@hiprax/use-seo/utils';
formatTitle('Contact', { template: '%s - My Site' }); // 'Contact - My Site'
formatTitle('Contact', { suffix: 'My Site' }); // 'Contact | My Site'
formatTitle('Contact', { prefix: 'My Site' }); // 'My Site | Contact'
formatTitle('Contact', { prefix: 'Prefix', suffix: 'Suffix' }); // 'Prefix | Contact | Suffix'
formatTitle('Contact', { template: '{title} | MyBrand' }); // 'Contact | MyBrand'
```
--------------------------------
### Quick Start with useSEO hook
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Basic usage of the useSEO hook in a React component to set SEO meta tags.
```tsx
import { useSEO } from '@hiprax/use-seo';
// or: import useSEO from '@hiprax/use-seo';
function ProductPage() {
useSEO({
title: 'Amazing Product',
titleSuffix: 'My Store',
description:
'The best product you will ever find. High quality and great value.',
canonical: 'https://mystore.com/products/amazing-product',
ogImage: 'https://mystore.com/images/product.jpg',
});
return
Product content
;
}
```
--------------------------------
### warn usage example
Source: https://github.com/hiprax/use-seo
Example of calling warn with a message and enabled flag. Outputs '[useSEO Warning]: Title is too long' to the console in development mode.
```ts
import { warn } from '@hiprax/use-seo/utils';
warn('Title is too long', true);
// console: [useSEO Warning]: Title is too long
```
--------------------------------
### buildRobots usage examples
Source: https://github.com/hiprax/use-seo
Shows string shorthand, explicit positive directives, and a mixed object with googlebot. String input is passed through directly; object input serializes with tri-state semantics. The googlebot field is serialized similarly.
```TypeScript
import { buildRobots } from '@hiprax/use-seo/utils';
// String input
buildRobots('noindex,nofollow');
// { robots: 'noindex,nofollow' }
// Explicit positive directives (useful to override a parent robots tag)
buildRobots({ index: true, follow: true });
// { robots: 'index,follow' }
// Mixed object with googlebot
buildRobots({
index: true,
follow: true,
maxSnippet: 150,
googlebot: { maxVideoPreview: 0 },
});
// { robots: 'index,follow,max-snippet:150', googlebot: 'max-video-preview:0' }
```
--------------------------------
### Check npm signatures and attestations
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Verifies the signatures and provenance attestations of the installed use-seo package. Every version published since v0.3.0 carries a signed attestation linking the tarball to the commit and workflow run that produced it.
```bash
npm audit signatures
```
--------------------------------
### getCurrentSEO usage example
Source: https://github.com/hiprax/use-seo
Example showing how to call getCurrentSEO to retrieve the current configuration. It logs the title and ogType, and demonstrates that mutating the returned clone does not affect the internal snapshot.
```tsx
const { getCurrentSEO } = useSEO({ title: 'Page', ogType: 'article' });
const current = getCurrentSEO();
console.log(current.title); // 'Page'
console.log(current.ogType); // 'article'
// Callers may mutate the returned clone without corrupting the internal snapshot
getCurrentSEO().ogImages?.push({ url: 'https://example.com/extra.jpg' });
```
--------------------------------
### clearSEOTags usage example
Source: https://github.com/hiprax/use-seo
Example showing how to call clearSEOTags to remove all tags created by the hook. The comment notes it removes all tags created by the hook.
```tsx
const { useSEO, clearSEOTags } = { useSEO, ...useSEO({ title: 'Page' }) };
clearSEOTags(); // removes all tags created by the hook
```
--------------------------------
### canUseDOM usage example
Source: https://github.com/hiprax/use-seo
Example of using canUseDOM to conditionally set the document title only when the DOM is available.
```ts
import { canUseDOM } from '@hiprax/use-seo/utils';
if (canUseDOM()) {
document.title = 'New Title';
}
```
--------------------------------
### fnv1aHash usage example
Source: https://github.com/hiprax/use-seo
Imports fnv1aHash from '@hiprax/use-seo' and hashes a JSON string. The result is a base-36 string (e.g., 'fv3slj') usable as a Map key or data-* attribute.
```ts
import { fnv1aHash } from '@hiprax/use-seo';
const h = fnv1aHash(JSON.stringify({ '@type': 'Article' }));
// e.g. 'fv3slj' — usable as a Map key or data-* attribute
```
--------------------------------
### normalizeLanguageTag usage example
Source: https://github.com/hiprax/use-seo
Example usage of normalizeLanguageTag showing normalization of various language tags and undefined for invalid input.
```TypeScript
import { normalizeLanguageTag } from '@hiprax/use-seo/utils';
normalizeLanguageTag('en'); // 'en'
normalizeLanguageTag('EN-us'); // 'en-US'
normalizeLanguageTag('zh-Hant-TW'); // 'zh-Hant-TW'
normalizeLanguageTag('en-US-u-ca-buddhist'); // 'en-US-u-ca-buddhist'
normalizeLanguageTag('invalid!!'); // undefined
```
--------------------------------
### buildRobotsFromFlags usage examples
Source: https://github.com/hiprax/use-seo
Shows mapping of noindex and nofollow flags to index/follow false, and that an empty flags object returns undefined. Marked @deprecated for backwards compatibility.
```TypeScript
import { buildRobotsFromFlags } from '@hiprax/use-seo/utils';
buildRobotsFromFlags({ noindex: true, nofollow: false });
// { index: false, follow: undefined }
buildRobotsFromFlags({});
// undefined
```
--------------------------------
### updateMetaTag Usage Examples (Object and Legacy Forms)
Source: https://github.com/hiprax/use-seo
Shows the preferred object key form and the deprecated legacy string form. The object form uses exactly one of name, property, or httpEquiv. The legacy form treats the first argument as a name, and an empty string with a property argument is treated as a property key.
```tsx
// Object key form (preferred)
const { updateMetaTag } = useSEO({});
updateMetaTag({ name: 'description' }, 'New description');
updateMetaTag({ property: 'og:title' }, 'New OG Title');
// Deprecated legacy string form with property
updateMetaTag('description', 'New description');
updateMetaTag('', 'title value', 'og:title');
```
--------------------------------
### inferImageMimeType usage examples
Source: https://github.com/hiprax/use-seo
Shows typical calls with different file extensions. Returns the corresponding MIME type for known extensions (case-insensitive) and `undefined` when the extension is not recognized.
```TypeScript
inferImageMimeType('https://example.com/image.jpg'); // 'image/jpeg'
inferImageMimeType('https://example.com/image.png'); // 'image/png'
inferImageMimeType('https://example.com/photo.heic'); // 'image/heic'
inferImageMimeType('https://example.com/page'); // undefined
```
--------------------------------
### getOrCreateMeta usage examples
Source: https://github.com/hiprax/use-seo
Shows basic usage and usage with a caller-side tracking Set. When preventDuplicates is true, trailing duplicate meta elements are removed. A brand-new element is added to the tracking set; a reused element is not added.
```TypeScript
const meta = getOrCreateMeta({ name: 'description' }, true);
meta?.setAttribute('content', 'Page description');
// With caller-side tracking Set
const tracked = new Set();
getOrCreateMeta({ name: 'description' }, true, tracked);
```
--------------------------------
### getOrCreateMeta
Source: https://github.com/hiprax/use-seo
Gets an existing meta element matching the key, or creates one if none exists. Optionally prevents duplicates and tracks ownership.
```APIDOC
## getOrCreateMeta
### Description
Gets an existing meta element matching the key, or creates one if none exists. Optionally prevents duplicates and tracks ownership.
### Signature
```ts
export function getOrCreateMeta(
key: MetaKey,
preventDuplicates: boolean,
trackedElements?: Set
): HTMLMetaElement | null
```
### Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `key` | `MetaKey` | Yes | — | Meta tag identifier; must contain at least one non-empty `name`/`property`/`httpEquiv`, otherwise `null` is returned. |
| `preventDuplicates` | `boolean` | Yes | — | When `true`, removes trailing duplicate meta elements matching the selector. |
| `trackedElements` | `Set` | No | — | Caller-owned set of created elements for later cleanup. A brand-new element is `add()`ed; a reused element is deliberately NOT added (it may belong to another `useSEO` instance). Removed duplicates are `delete()`d. |
### Return type
`HTMLMetaElement | null` — the existing or newly created element, or `null` when no key was provided.
### Request Example
```ts
const meta = getOrCreateMeta({ name: 'description' }, true);
meta?.setAttribute('content', 'Page description');
// With caller-side tracking Set
const tracked = new Set();
getOrCreateMeta({ name: 'description' }, true, tracked);
```
```
--------------------------------
### updateLinkTag usage examples (modern and legacy forms)
Source: https://github.com/hiprax/use-seo
Shows how to call updateLinkTag from useSEO. Covers adding a preconnect link, a preload link with attributes (modern form), the legacy string-attribute form, and unique enforcement by passing undefined attrs with a boolean fourth argument.
```TSX
const { updateLinkTag } = useSEO({});
// Add a preconnect link
updateLinkTag('preconnect', 'https://fonts.googleapis.com');
// Add a preload link with attributes (modern form)
updateLinkTag('preload', '/font.woff2', {
as: 'font',
type: 'font/woff2',
crossOrigin: 'anonymous',
});
// Legacy string-attribute form
updateLinkTag('preload', '/font.woff2', 'font/woff2', undefined, undefined, undefined, 'anonymous');
// Only want unique enforcement: pass undefined attrs + boolean fourth arg
updateLinkTag('canonical', 'https://example.com/page', undefined, true);
```
--------------------------------
### Import useSEO from @hiprax/use-seo
Source: https://github.com/hiprax/use-seo
Import the main hook from the package root. This is the standard way to bring useSEO into your project.
```TypeScript
import { useSEO } from '@hiprax/use-seo';
```
--------------------------------
### Available npm Scripts for Development
Source: https://github.com/hiprax/use-seo/blob/main/README.md
List of npm scripts for building, testing, linting, formatting, type-checking, and cleaning the project. Use `npm run build` to build the library with tsup, `npm run dev` for watch mode, `npm run test` for tests, `npm run test:watch` for watch mode, `npm run test:coverage` for coverage, `npm run lint` for linting, `npm run lint:fix` to auto-fix, `npm run format` to format with Prettier, `npm run format:check` to check formatting, `npm run typecheck` for TypeScript type checking, and `npm run clean` to remove dist and coverage directories.
```bash
# Build the library (uses tsup)
npm run build
# Watch mode for development
npm run dev
# Run tests
npm run test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Lint source files
npm run lint
# Lint and auto-fix
npm run lint:fix
# Format source files with Prettier
npm run format
# Check formatting without writing
npm run format:check
# TypeScript type checking (no emit)
npm run typecheck
# Remove dist and coverage directories
npm run clean
```
--------------------------------
### fnv1aHash
Source: https://github.com/hiprax/use-seo
FNV-1a string hash utility re-exported for advanced consumers to build custom change-detection or cache-invalidation flows.
```APIDOC
## fnv1aHash
### Description
FNV-1a string hash utility re-exported for advanced consumers to build custom change-detection or cache-invalidation flows.
### Method
function
### Signature
`fnv1aHash(input: string): string`
### Parameters
- `input` (string) - Required - The string to hash.
### Returns
`string` - The FNV-1a hash of the input string.
```
--------------------------------
### isUrlField usage example
Source: https://github.com/hiprax/use-seo
Example usage of isUrlField showing true for URL fields and false for non-URL fields.
```TypeScript
import { isUrlField } from '@hiprax/use-seo/utils';
isUrlField('og:image'); // true
isUrlField('description'); // false
isUrlField('imagealt'); // false (no boundary)
```
--------------------------------
### Project Directory Structure
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Shows the source file layout for the use-seo package. The main hook is in useSEO.ts, types in types.ts, constants in constants.ts, and utilities in the utils/ directory with files for DOM helpers, validation, robots directives, title formatting, and development warnings.
```text
src/
index.ts # Public API exports
useSEO.ts # Main hook implementation
types.ts # TypeScript type definitions
constants.ts # Default values and limits
utils/
index.ts # Barrel re-export for utilities
dom.ts # DOM manipulation helpers
validation.ts # URL and language validation
robots.ts # Robots directive builder
title.ts # Title formatting logic
warnings.ts # Development warning utilities
```
--------------------------------
### Package.json module format configuration
Source: https://github.com/hiprax/use-seo
Shows the dual ESM/CJS build configuration with TypeScript types. The package ships both import and require entry points, and is marked sideEffects: false.
```JSON
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" },
"require": { "types": "./dist/index.d.ts", "default": "./dist/index.cjs" }
}
}
```
--------------------------------
### normalizeCanonical usage example
Source: https://github.com/hiprax/use-seo
Example usage of normalizeCanonical from '@hiprax/use-seo/utils'. Returns the URL with the hash fragment removed, or resolves relative paths against the current domain when the DOM is available.
```TypeScript
import { normalizeCanonical } from '@hiprax/use-seo/utils';
normalizeCanonical('https://example.com/page#section');
// 'https://example.com/page'
normalizeCanonical('/relative/path');
// 'https://current-domain.com/relative/path' (with DOM)
```
--------------------------------
### isValidUrl usage example
Source: https://github.com/hiprax/use-seo
Example usage of isValidUrl from '@hiprax/use-seo/utils'. Returns true for absolute URLs, true for relative URLs when allowRelative is true and the DOM is available, and false for invalid strings.
```TypeScript
import { isValidUrl } from '@hiprax/use-seo/utils';
isValidUrl('https://example.com'); // true
isValidUrl('/path/to/page', true); // true (relative + DOM)
isValidUrl('not-a-url'); // false
```
--------------------------------
### Basic SEO configuration with useSEO
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures core SEO meta tags including title, description, keywords, canonical URL, language, and author. The title and description have recommended character lengths, and autoCanonical defaults to true.
```tsx
useSEO({
// Page title (recommended: 30-60 characters)
title: 'Page Title',
// Meta description (recommended: 120-160 characters)
description: 'A compelling description of your page content.',
// Meta keywords (comma-separated, max 10 recommended)
keywords: 'react, seo, meta tags',
// Canonical URL
canonical: 'https://example.com/page',
// Auto-generate canonical from current URL (default: true)
autoCanonical: true,
// Page language (sets )
language: 'en',
// Content author
author: 'John Doe',
});
```
--------------------------------
### Open Graph audio configuration with useSEO
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures og:audio meta tags with full metadata via ogAudios or a single URL via ogAudio shorthand. Emits og:audio, og:audio:secure_url, and og:audio:type. URLs are validated against validateUrls.
```tsx
useSEO({
ogAudios: [
{
url: 'https://example.com/audio.mp3',
type: 'audio/mpeg',
},
],
});
// Single-audio shorthand
useSEO({
ogAudio: 'https://example.com/audio.mp3',
});
```
--------------------------------
### clearSEOTags in a component
Source: https://github.com/hiprax/use-seo
Example of using clearSEOTags inside a React component, triggered by a button click. The comment indicates navigation away.
```tsx
import { useSEO } from '@hiprax/use-seo';
function Nav() {
const { clearSEOTags } = useSEO({ title: 'Products' });
return ;
}
```
--------------------------------
### Import Constants from @hiprax/use-seo
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Import the package's exported constants for customization. The constants include DEFAULT_OG_TYPE ('website'), DEFAULT_TWITTER_CARD ('summary_large_image'), DEFAULT_AUTO_CANONICAL (true), DEFAULT_PREVENT_DUPLICATES (true), DEFAULT_VALIDATE_URLS (true), MIN_TITLE_LENGTH (30), MAX_TITLE_LENGTH (60), MIN_DESCRIPTION_LENGTH (120), MAX_DESCRIPTION_LENGTH (160), and MAX_KEYWORDS_COUNT (10).
```tsx
import {
DEFAULT_OG_TYPE, // 'website'
DEFAULT_TWITTER_CARD, // 'summary_large_image'
DEFAULT_AUTO_CANONICAL, // true
DEFAULT_PREVENT_DUPLICATES, // true
DEFAULT_VALIDATE_URLS, // true
MIN_TITLE_LENGTH, // 30
MAX_TITLE_LENGTH, // 60
MIN_DESCRIPTION_LENGTH, // 120
MAX_DESCRIPTION_LENGTH, // 160
MAX_KEYWORDS_COUNT, // 10
} from '@hiprax/use-seo';
```
--------------------------------
### useSEO
Source: https://github.com/hiprax/use-seo
The main React hook for managing SEO metadata. It accepts an SEO configuration object and applies it to the document head.
```APIDOC
## useSEO
### Description
The main React hook for managing SEO metadata. It accepts an SEO configuration object and applies it to the document head.
### Method
function
### Signature
`useSEO(options: SEOProps): SEOHookReturn`
### Parameters
#### options (SEOProps) - Required
- `title` (string) - Required - The page title.
- `description` (string) - Optional - The meta description.
- `ogImage` (string) - Optional - The Open Graph image URL.
### Returns
`SEOHookReturn` - The return type of `useSEO`.
### Request Example
```tsx
import { useSEO } from 'use-seo';
function MyPage() {
useSEO({
title: 'My Amazing Page',
description: 'This is the best page ever',
ogImage: 'https://example.com/og.jpg',
});
return
Content
;
}
```
```
--------------------------------
### useSEO - Pagination
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Set prev and next link tags for paginated content, helping search engines understand the relationship between pages.
```APIDOC
## useSEO - Pagination
### Description
Set prev and next link tags for paginated content, helping search engines understand the relationship between pages.
### Method
useSEO (hook)
### Parameters
#### prev (string) - Optional - URL of the previous page
#### next (string) - Optional - URL of the next page
### Request Example
```tsx
useSEO({
prev: 'https://example.com/posts?page=1',
next: 'https://example.com/posts?page=3',
});
```
```
--------------------------------
### getOrCreateMeta signature
Source: https://github.com/hiprax/use-seo
Gets an existing meta element matching the key, or creates one if none exists. Optionally prevents duplicates and tracks ownership.
```TypeScript
export function getOrCreateMeta(
key: MetaKey,
preventDuplicates: boolean,
trackedElements?: Set
): HTMLMetaElement | null
```
--------------------------------
### getOrCreateLink(rel, unique, keySelector?, trackedElements?)
Source: https://github.com/hiprax/use-seo
Gets an existing link element matching the relationship, or creates one. Supports uniqueness constraints and key selectors.
```APIDOC
## getOrCreateLink(rel, unique, keySelector?, trackedElements?)
### Description
Gets an existing link element matching the relationship, or creates one. Supports uniqueness constraints and key selectors.
### Signature
```ts
export function getOrCreateLink(
rel: string,
unique: boolean,
keySelector?: string,
trackedElements?: Set
): HTMLLinkElement
```
### Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `rel` | `string` | Yes | — | The link relationship type. |
| `unique` | `boolean` | Yes | — | When `true` and no `keySelector` is supplied, removes all but the first `link[rel="..."]` element. |
| `keySelector` | `string` | No | — | Additional selector to identify specific links (e.g. `'[hreflang="en"]'`). |
| `trackedElements` | `Set` | No | — | Same ownership/dedup bookkeeping semantics as `getOrCreateMeta`. |
### Return type
`HTMLLinkElement` — the existing or newly created link element.
### Request Example
```ts
const link = getOrCreateLink('canonical', true);
link.setAttribute('href', 'https://example.com/page');
// With key selector for hreflang
const hreflangLink = getOrCreateLink('alternate', false, '[hreflang="en"]');
```
```
--------------------------------
### clearSEOTags()
Source: https://github.com/hiprax/use-seo
A method returned by `useSEO` that clears all SEO tags managed by the hook from the document head. It is typically used to reset the head, for example on a button click.
```APIDOC
## clearSEOTags()
### Description
A method returned by `useSEO` that clears all SEO tags managed by the hook from the document head. It is typically used to reset the head, for example on a button click.
### Method
Function call (part of `SEOHookReturn`)
### Parameters
None.
### Request Example
```tsx
```
```
--------------------------------
### Pagination
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Set prev and next URLs for pagination.
```tsx
useSEO({
prev: 'https://example.com/posts?page=1',
next: 'https://example.com/posts?page=3',
});
```
--------------------------------
### useSEO - Basic SEO
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures basic SEO meta tags for a page, including title, description, keywords, canonical URL, language, and author.
```APIDOC
## useSEO - Basic SEO
### Description
Configures basic SEO meta tags for a page, including title, description, keywords, canonical URL, language, and author.
### Method
useSEO()
### Parameters
#### Options Object
- **title** (string) - Optional - Page title (recommended: 30-60 characters)
- **description** (string) - Optional - Meta description (recommended: 120-160 characters)
- **keywords** (string) - Optional - Meta keywords (comma-separated, max 10 recommended)
- **canonical** (string) - Optional - Canonical URL
- **autoCanonical** (boolean) - Optional - Auto-generate canonical from current URL (default: true)
- **language** (string) - Optional - Page language (sets )
- **author** (string) - Optional - Content author
### Request Example
```tsx
useSEO({
// Page title (recommended: 30-60 characters)
title: 'Page Title',
// Meta description (recommended: 120-160 characters)
description: 'A compelling description of your page content.',
// Meta keywords (comma-separated, max 10 recommended)
keywords: 'react, seo, meta tags',
// Canonical URL
canonical: 'https://example.com/page',
// Auto-generate canonical from current URL (default: true)
autoCanonical: true,
// Page language (sets )
language: 'en',
// Content author
author: 'John Doe',
});
```
```
--------------------------------
### useSEO()
Source: https://github.com/hiprax/use-seo/blob/main/README.md
The main hook that manages SEO tags. It accepts an SEO configuration object and returns methods for programmatic tag management.
```APIDOC
## useSEO()
### Description
The main hook that manages SEO tags. It accepts an SEO configuration object and returns methods for programmatic tag management.
### Parameters
#### Hook Arguments
- **SEOProps** (object) - Required - Configuration object with properties like `title`, `description`, etc.
### Returns
- **updateMetaTag** (function) - Updates a meta tag
- **updateLinkTag** (function) - Updates a link tag
- **clearSEOTags** (function) - Removes all SEO tags added by this hook
- **getCurrentSEO** (function) - Returns the current SEO configuration
### Request Example
```tsx
const { updateMetaTag, updateLinkTag, clearSEOTags, getCurrentSEO } = useSEO({
title: 'My Page',
});
```
```
--------------------------------
### Stabilize props with useMemo for useSEO
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Recommended pattern to avoid unnecessary effect re-runs: wrap the SEO props object in useMemo so the same reference is reused across renders that don't change the underlying data. The dependency array [page] ensures the memo updates only when the page object changes.
```tsx
const seoProps = useMemo(
() => ({
title: page.title,
description: page.description,
canonical: page.canonical,
ogImages: page.images, // stable reference per `page` change
}),
[page]
);
useSEO(seoProps);
```
--------------------------------
### buildRobots
Source: https://github.com/hiprax/use-seo
Builds robots and optional googlebot meta tag content from a string or object configuration. Returns a RobotsResult object containing the robots and googlebot meta tag strings.
```APIDOC
## buildRobots
### Description
Builds `robots` and optional `googlebot` meta tag content from a string or object configuration.
### Signature
```ts
export function buildRobots(options?: RobotsOptions): RobotsResult
```
### Parameters
- `options` (RobotsOptions) - Optional - A string shorthand (e.g. `'noindex,nofollow'`) or a granular `RobotsObject`.
### Return Type
`RobotsResult`
### Behavior
- String input: trimmed and passed through directly (or `{}` if empty).
- Object input: serialized via the internal `robotsObjectToString` (not exported) with tri-state semantics:
- `index`/`follow` `=== true` → emit positive directive (`index`/`follow`); `=== false` → negative (`noindex`/`nofollow`); `undefined` → omit.
- `noarchive`, `nosnippet`, `noimageindex` only emit when explicitly `true`.
- `maxSnippet`/`maxVideoPreview` map the legacy `'none'`/`0` value to `0` (per Google, `max-snippet`/`max-video-preview` only accept an integer; there is no literal `none`).
- `maxImagePreview` emits its literal value (`none`/`standard`/`large`) — Google genuinely accepts `none` here.
- `unavailableAfter` is appended verbatim as `unavailable_after: `.
- The `googlebot` field, if present, is serialized the same way (a string passes through; an object is serialized via `robotsObjectToString`).
A whole object that serializes to an empty string yields `robots: undefined`.
### Request Example
```ts
import { buildRobots } from '@hiprax/use-seo/utils';
// String input
buildRobots('noindex,nofollow');
// { robots: 'noindex,nofollow' }
// Explicit positive directives (useful to override a parent robots tag)
buildRobots({ index: true, follow: true });
// { robots: 'index,follow' }
// Mixed object with googlebot
buildRobots({
index: true,
follow: true,
maxSnippet: 150,
googlebot: { maxVideoPreview: 0 },
});
// { robots: 'index,follow,max-snippet:150', googlebot: 'max-video-preview:0' }
```
```
--------------------------------
### useSEO - Open Graph Audio
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures Open Graph audio meta tags, supporting full metadata via ogAudios or a single URL via ogAudio.
```APIDOC
## useSEO - Open Graph Audio
### Description
Configures Open Graph audio meta tags, supporting full metadata via ogAudios or a single URL via ogAudio.
### Method
useSEO()
### Parameters
#### Options Object
- **ogAudios** (array) - Optional - Array of audio objects with url and type
- **ogAudio** (string) - Optional - Single audio URL shorthand
### Request Example
```tsx
useSEO({
ogAudios: [
{
url: 'https://example.com/audio.mp3',
type: 'audio/mpeg',
},
],
});
// Single-audio shorthand
useSEO({
ogAudio: 'https://example.com/audio.mp3',
});
```
```
--------------------------------
### JSON.stringify key order sensitivity example
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Shows that JSON.stringify serializes object keys in insertion order, so objects with identical data but different key order produce different strings. This is the core mechanism behind the hook's change detection.
```javascript
JSON.stringify({ a: 1, b: 2 }); // '{"a":1,"b":2}'
JSON.stringify({ b: 2, a: 1 }); // '{"b":2,"a":1}'
```
--------------------------------
### useSEO - Robots Directives
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configure robots meta tag directives for search engine crawling and indexing. Supports both simple string and detailed object formats, with tri-state semantics for index/follow and special handling for maxSnippet and maxVideoPreview values.
```APIDOC
## useSEO - Robots Directives
### Description
Configure robots meta tag directives for search engine crawling and indexing. Supports both simple string and detailed object formats, with tri-state semantics for index/follow and special handling for maxSnippet and maxVideoPreview values.
### Method
useSEO (hook)
### Parameters
#### robots (string | object) - Optional
- **robots** (string) - Simple string format, e.g., 'noindex,nofollow'
- **robots.index** (boolean) - Optional - true emits 'index', false emits 'noindex', undefined omits
- **robots.follow** (boolean) - Optional - true emits 'follow', false emits 'nofollow', undefined omits
- **robots.noarchive** (boolean) - Optional - false omits, true emits 'noarchive'
- **robots.nosnippet** (boolean) - Optional - false omits, true emits 'nosnippet'
- **robots.noimageindex** (boolean) - Optional - false omits, true emits 'noimageindex'
- **robots.maxSnippet** (number | 'none') - Optional - Integer or 'none' (mapped to 0)
- **robots.maxImagePreview** (string) - Optional - Accepts 'none' or size like 'large'
- **robots.maxVideoPreview** (number | 'none') - Optional - Integer or 'none' (mapped to 0)
- **robots.unavailableAfter** (string) - Optional - RFC 850 or ISO 8601 datetime
- **robots.googlebot** (object) - Optional - Googlebot-specific directives
- **googlebot.index** (boolean) - Optional
- **googlebot.follow** (boolean) - Optional
- **googlebot.maxVideoPreview** (number) - Optional
### Deprecated Boolean Props
- **noindex** (boolean) - Deprecated - Use robots.index instead
- **nofollow** (boolean) - Deprecated - Use robots.follow instead
- **noarchive** (boolean) - Deprecated - Use robots.noarchive instead
- **nosnippet** (boolean) - Deprecated - Use robots.nosnippet instead
- **noimageindex** (boolean) - Deprecated - Use robots.noimageindex instead
### Precedence
When both `robots` and deprecated boolean flags are passed, `robots` wins. Deprecated flags are only consulted when `robots` is `undefined`.
### Request Example
```tsx
// Simple string format
useSEO({
robots: 'noindex,nofollow',
});
// Detailed object format
useSEO({
robots: {
index: true,
follow: true,
noarchive: false,
nosnippet: false,
noimageindex: false,
maxSnippet: 150,
maxImagePreview: 'large',
maxVideoPreview: 30,
unavailableAfter: '2025-12-31T23:59:59Z',
googlebot: {
index: true,
follow: true,
maxVideoPreview: 0,
},
},
});
```
```
--------------------------------
### formatTitle
Source: https://github.com/hiprax/use-seo
Formats a title by applying prefix, suffix, or template options. Returns the formatted title string.
```APIDOC
## formatTitle
### Description
Formats a title by applying prefix, suffix, or template options. Returns the formatted title string.
### Signature
```ts
function formatTitle(title: string, options?: TitleFormatOptions): string
```
### Parameters
- `title` (string) - Required - The base title to format.
- `options` (TitleFormatOptions) - Optional - Formatting options (prefix, suffix, template, separator).
### Returns
- `string` - The formatted title.
### Example
```ts
import { formatTitle } from '@hiprax/use-seo/utils/title';
formatTitle('My Page', { prefix: 'Site' });
// Returns: 'Site | My Page'
```
```
--------------------------------
### Open Graph configuration with useSEO
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures Open Graph meta tags for social sharing, including type, site name, title, description, URL, locale, and images. Supports both single image (ogImage) and multiple images (ogImages) with full metadata.
```tsx
useSEO({
// OG type (default: 'website')
ogType: 'article',
// Site name
ogSiteName: 'My Website',
// OG title (falls back to formatted title)
ogTitle: 'Article Title',
// OG description (falls back to description)
ogDescription: 'Article description for social sharing.',
// OG URL (falls back to canonical)
ogUrl: 'https://example.com/article',
// Locale
ogLocale: 'en_US',
// Alternate locales
ogLocaleAlternates: ['en_GB', 'de_DE', 'fr_FR'],
// Single image (simple)
ogImage: 'https://example.com/og-image.jpg',
ogImageWidth: 1200,
ogImageHeight: 630,
ogImageAlt: 'Description of the image',
// Multiple images with full metadata (preferred)
ogImages: [
{
url: 'https://example.com/image1.jpg',
width: 1200,
height: 630,
alt: 'Primary image',
type: 'image/jpeg',
secureUrl: 'https://example.com/image1.jpg', // optional, auto-inferred for https URLs
},
{
url: 'https://example.com/image2.png',
width: 800,
height: 600,
alt: 'Secondary image',
},
],
});
```
--------------------------------
### useSEO - Title Formatting
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures title formatting options such as suffix, prefix, template, and separator.
```APIDOC
## useSEO - Title Formatting
### Description
Configures title formatting options such as suffix, prefix, template, and separator.
### Method
useSEO()
### Parameters
#### Options Object
- **title** (string) - Required - Page title
- **titleSuffix** (string) - Optional - Suffix appended to the title
- **titlePrefix** (string) - Optional - Prefix prepended to the title
- **titleTemplate** (string) - Optional - Template with %s or {title} placeholder
- **titleSeparator** (string) - Optional - Custom separator (default: ' | ')
### Request Example
```tsx
// With suffix (result: "Contact | My Site")
useSEO({
title: 'Contact',
titleSuffix: 'My Site',
});
// With prefix (result: "My Site | Contact")
useSEO({
title: 'Contact',
titlePrefix: 'My Site',
});
// With template using %s placeholder
useSEO({
title: 'Contact',
titleTemplate: '%s - My Website',
});
// With template using {title} placeholder
useSEO({
title: 'Contact',
titleTemplate: '{title} | Brand',
});
// With custom separator (default: ' | ')
useSEO({
title: 'Contact',
titleSuffix: 'My Site',
titleSeparator: ' - ',
// Result: "Contact - My Site"
});
```
```
--------------------------------
### Open Graph video configuration with useSEO
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Configures og:video meta tags with full metadata via ogVideos or a single URL via ogVideo shorthand. secureUrl is auto-inferred for https URLs. Emits og:video, og:video:secure_url, og:video:type, og:video:width, og:video:height, and og:video:alt. Stale tags are cleaned up on re-render when the prop is removed.
```tsx
useSEO({
ogVideos: [
{
url: 'https://example.com/video.mp4',
type: 'video/mp4',
width: 1280,
height: 720,
alt: 'Demo video',
// secureUrl is auto-inferred when `url` starts with https:
secureUrl: 'https://example.com/video.mp4',
},
],
});
// Single-video shorthand (mirrors the legacy `ogImage` form)
useSEO({
ogVideo: 'https://example.com/video.mp4',
});
```
--------------------------------
### Next.js Pages Router with Head and Client Component
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Renders static tags inside and calls useSEO from a child client component for dynamic ones in the Pages Router. The Page component includes the static title in Head and renders ClientSideComponent, which uses useSEO with a dynamic title.
```tsx
import Head from 'next/head';
import { useSEO } from '@hiprax/use-seo';
function Page() {
return (
<>
My Page
>
);
}
function ClientSideComponent() {
useSEO({ title: 'Dynamic Title' });
return
Content
;
}
```
--------------------------------
### Run test coverage report
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Reproduces the Jest coverage report for the use-seo package. The suite ships 538 tests with 98.67% statements, 95.33% branches, 100% functions, and 100% lines as of v0.3.3; exact numbers may vary slightly per release.
```bash
npm run test:coverage
```
--------------------------------
### canUseDOM()
Source: https://github.com/hiprax/use-seo
Checks whether the DOM is available (client-side environment). The result is cached after the first call.
```APIDOC
## canUseDOM()
### Description
Checks whether the DOM is available (client-side environment). The result is cached after the first call.
### Signature
```ts
export function canUseDOM(): boolean
```
### Parameters
None.
### Return Type
`boolean` — `true` when `window`, `document`, and `document.createElement` are all available.
### Example
```ts
import { canUseDOM } from '@hiprax/use-seo/utils';
if (canUseDOM()) {
document.title = 'New Title';
}
```
```
--------------------------------
### Referrer, format-detection, and no-translate meta tags
Source: https://github.com/hiprax/use-seo/blob/main/README.md
Set referrer policy, format detection, Google no-translate, and site verification via additionalMetaTags. Use the exact content values shown for each meta tag.
```tsx
useSEO({
additionalMetaTags: [
{ name: 'referrer', content: 'strict-origin-when-cross-origin' },
{ name: 'format-detection', content: 'telephone=no, email=no' },
{ name: 'google', content: 'notranslate' },
{ name: 'google-site-verification', content: 'YOUR-VERIFICATION-TOKEN' },
],
});
```
--------------------------------
### Import and use constants from @hiprax/use-seo
Source: https://github.com/hiprax/use-seo
Shows how to import DEFAULT_OG_TYPE and MAX_TITLE_LENGTH from the package root. Logs the default ogType ('website') and the recommended maximum title length (60).
```TypeScript
import {
DEFAULT_OG_TYPE,
MAX_TITLE_LENGTH,
} from '@hiprax/use-seo';
console.log(DEFAULT_OG_TYPE); // 'website'
console.log(MAX_TITLE_LENGTH); // 60
```
--------------------------------
### canUseDOM function signature
Source: https://github.com/hiprax/use-seo
Checks whether the DOM is available (client-side environment). Returns true when window, document, and document.createElement are all available. The result is cached after the first call.
```ts
export function canUseDOM(): boolean
```