Utilities
API reference for form validation, URL, text, math, time, email, docs, route, scheduling, and SEO utility functions across Nuxtify modules.
Overview
Nuxtify auto-imports utility functions from each installed module. Shared utilities from @nuxtify/core are available in both app code and Nitro server routes, while module-specific helpers are auto-imported in app code (and server-only helpers in server/).
Core App Utilities (@nuxtify/core)
formRules
- Provided by:
@nuxtify/core - Source:
src/runtime/utils/formRules.ts
Vuetify-compatible field validation rules ((value) => true | string) ready to pass directly to :rules="[formRules.required, formRules.validEmail]".
| Rule | Validates |
|---|---|
required | Non-empty string value (!!v). |
requiredArray | Non-empty array (!!v.length). |
validEmail | Basic email pattern (/.+@.+/). |
minLength8, minLength12 | Minimum string length (passes when empty; pair with required). |
maxLength30, maxLength60, maxLength120, maxLength150, maxLength200, maxLength300, maxLength600, maxLength1200, maxLength5000, maxLength10000 | Maximum string length bounds. |
isInteger | Value parses as an integer (Number.isInteger(+v)). |
gt0, gte6, lte12, lte365 | Numeric range checks (> 0, >= 6, <= 12, <= 365). |
URL & Route Matching
- Provided by:
@nuxtify/core - Source:
src/runtime/utils/url.ts
| Function | Signature | Description |
|---|---|---|
getBaseUrl | (url: string) => string | Strips query parameters and hash fragments from a URL. |
getUtmParams | (url: string) => { utmSource, utmMedium, utmCampaign, utmTerm, utmContent } | Extracts standard utm_* query parameters (string | null). |
isExternalUrl | (url: string, hostname: string) => boolean | Returns true for absolute URLs whose hostname differs from hostname; returns false for empty or /-prefixed relative paths. |
matchRoute | (pattern: string, path: string) => boolean | Matches a route path against exact patterns, single-segment *, or recursive /** wildcards (used by AppAnnouncement). |
Core Shared Utilities (@nuxtify/core)
Available in both client/app code and Nitro server/ handlers.
Text Formatting
- Source:
src/runtime/shared/utils/text.ts
| Function | Signature | Description |
|---|---|---|
titleCase | (text: string, skipShortWords?: boolean) => string | Capitalizes words, optionally keeping short conjunctions/prepositions lowercase except as the first word (skipShortWords = true). |
capitalizeFirstLetter | (text: string) => string | Uppercases the first character of a string. |
fullName | (firstName: string, lastName: string) => string | Joins non-empty first and last names cleanly. |
parseFullName | (fullName?: string | null) => { firstName: string, lastName: string } | Splits a full name string into firstName and remaining lastName. |
honoraryName | (name: string, honorificSuffix?: string) => string | Formats "Name, Suffix" when a suffix is present. |
getPronouns | (gender: string) => { single, plural, possessive, possessivePlural } | Returns pronoun forms for 'male', 'female', or gender-neutral default ('they'). |
formatPhone | (input: string, separator?: string) => string | Strips a leading +1 and formats 10-digit US phone numbers with separator (default '-'). |
formatDate | (date: number | string | Date, config?) => string | Formats dates using Intl.DateTimeFormat (type: 'date' | 'datetime', locale, options, defaultString). |
booleanToText | (bool: boolean) => 'Yes' | 'No' | Converts a boolean into 'Yes' or 'No'. |
truncate | (text: string, maxLength?: number, ellipses?: boolean) => string | Truncates text at the nearest word boundary (maxLength = 80, ellipses = true). |
slugify | (text: string) => string | Normalizes Unicode (NFKD) and converts text into a lowercase hyphenated URL slug. |
unslugify | (text: string) => string | Replaces hyphens with spaces. |
pluralize | (value: number, units: string, showValue?: boolean) => string | Pluralizes unit nouns (handling trailing 'y' -> 'ies'), optionally prefixing the numeric value. |
getLanguageName | (languageCode: string, displayLanguage?: string) => string | undefined | Resolves BCP 47 language codes via Intl.DisplayNames with root-language fallback. |
addArticle | (text: string | undefined, includeText?: boolean) => string | Prepends (or returns) 'a' or 'an' based on the leading letter. |
Math, Time, Navigation & Misc
| Function | Source | Signature | Description |
|---|---|---|---|
toPercentage | math.ts | (val: number, decimals?: number) => string | Formats a decimal ratio (e.g., 0.42) as a percentage string ('42%'). |
roundToFixed | math.ts | (val: number | string, positions?: number) => number | Rounds a numeric value to positions decimal places (default 2). |
isTitledLinks | navigation.ts | (item: NavigationItem) => item is TitledLinks | Type guard distinguishing dropdown groups from flat Link items. |
delay | time.ts | (ms: number) => Promise<void> | Async sleep helper. |
daysSince | time.ts | (targetDate: Date) => number | Returns whole days elapsed since targetDate. |
addOrReplaceArrayItem | util.ts | (array, element) => void | Mutates an array of { id } objects, replacing a matching id or pushing if absent. |
getRandomInt | util.ts | (min: number, max: number) => number | Returns a uniform random integer between min and max (inclusive). |
youTubeUrl | youtube.ts | (url: string) => string | null | Extracts an 11-character YouTube video ID from common share/watch URLs and returns https://www.youtube.com/embed/<id>. |
Core Server Utilities (@nuxtify/core)
Auto-imported inside Nitro server/ routes only.
submitToAPI
- Provided by:
@nuxtify/core - Source:
src/runtime/server/utils/api.ts
Sends a JSON POST request with Authorization: Bearer <apiKey> and returns { res, isSubmitted, isError, errorMessage }.
const { res, isSubmitted, isError, errorMessage } = await submitToAPI(
apiKey,
'https://api.example.com/v1/subscribers',
JSON.stringify({ email }),
)
Email Utilities (@nuxtify/pages)
submitFormData
- Provided by:
@nuxtify/pages - Source:
src/runtime/utils/email.ts
Posts a FormData payload to submitUrl and returns { isSubmitted: boolean, isError: boolean, errorMessage: string }. Used internally by EmailSubscribeForm and available for custom form components.
const { isSubmitted, isError, errorMessage } = await submitFormData(submitUrl, formData)
CMS Utilities (@nuxtify/cms)
Docs Utilities
- Provided by:
@nuxtify/cms - Source:
src/runtime/utils/docs.ts
| Function | Signature | Description |
|---|---|---|
normalizeDocRoutePath | (path?: string) => string | Guarantees a leading slash and strips query strings, hashes, and trailing slashes. |
toDocsPublicPath | (contentPath: string, docsPrefix?: string) => string | Rewrites a /docs/... collection path to your configured docsPrefix. |
toDocsContentPath | (publicPath: string, docsPrefix?: string) => string | Maps an incoming public docs URL back to a /docs/... collection lookup path. |
unwrapDocsNavigationRoot | (tree, docsPrefix?) => ContentNavigationItem[] | Strips .navigation meta nodes, unwraps the root /docs folder, and normalizes paths. |
findFirstDocLeaf | (items) => ContentNavigationItem | null | Depth-first search returning the first navigable page in a docs tree (used for root and folder auto-redirects). |
resolveDocNavNode | (items, targetPath) => ContentNavigationItem | null | Finds a navigation node by normalized path anywhere in the tree. |
splitDocsNavigation | (items, currentPath) => DocsNavigationState | Splits top-level grouped directories into { categories, activeCategory, sidebarItems } for DocsTabs and DocsSidebar. |
buildDocsBreadcrumbs | (items, currentPath) => BreadcrumbItem[] | Builds the breadcrumb trail from the root category down to the active doc page. |
rewriteDocsSurroundings | (surroundings, docsPrefix?) => [prev, next] | Rewrites usePublicCollectionSurroundings results to honor custom docsPrefix. |
Route & Sitemap Utilities
- Provided by:
@nuxtify/cms - Source:
src/runtime/utils/routes.ts
| Function | Signature | Description |
|---|---|---|
normalizePrefix | (prefix?: string, fallback?: string) => string | Normalizes a route prefix to start with / and omit any trailing /. |
extractSlug | (item?: { stem?, path? } | string) => string | Extracts the trailing slug segment from a content item or path string. |
getContentItemLink | (prefix: string, item?) => string | Builds a flat collection permalink (${normalizedPrefix}/${slug}). |
getDocsItemLink | (prefix: string, item?) => string | Builds a nested docs permalink, preserving hierarchy and stripping numeric ordering prefixes. |
isNavigationMetaItem | (item?: { stem?, path? }) => boolean | Returns true for Nuxt Content .navigation metadata entries. |
applyContentSitemapMeta | (ctx: ContentAfterParseContext) => void | Build-time hook helper normalizing publishedAt to UTC ISO-8601, excluding .navigation/draft/disabled items from sitemap and robots, and mapping sitemap.loc to custom routePrefix values. (Future-dated publishedAt sitemap exclusion is handled dynamically at runtime via createSeoSchema from @nuxtify/cms/content.) |
Scheduling Utilities
- Provided by:
@nuxtify/cms - Source:
src/runtime/utils/scheduling.ts
| Export | Type / Signature | Description |
|---|---|---|
DEFAULT_SCHEDULED_COLLECTIONS | readonly ['articles', 'notes', 'pages', 'docs'] | Default collection names filtered by future publishedAt. |
parsePublishedAt | (value: unknown) => Date | null | Safely parses string | Date timestamps into a valid Date or null. |
normalizePublishedAtUtc | (value: unknown) => string | undefined | Converts valid dates to 24-character UTC ISO-8601 strings (YYYY-MM-DDTHH:mm:ss.sssZ) so SQLite comparisons match UTC epoch order. |
isScheduledFuture | (value: unknown, now?: Date | number) => boolean | Returns true when value is strictly after now. |
shouldFilterScheduledCollection | (collection, scheduledCollections?, override?) => boolean | Resolves whether scheduled-content filtering applies for a collection. |
SEO & Schema Builders
- Provided by:
@nuxtify/cms - Source:
src/runtime/utils/seo.ts
Low-level pure builders backing useContentPageSchema, useArticleSchema, useDocSchema, PageFaq, and useSeoMeta:
| Function | Description |
|---|---|
getBreadcrumbsSchema(breadcrumbs, currentItem?) | Normalizes BreadcrumbItem[] into Schema.org ListItem entries (returns [] if fewer than 2 valid items). |
stripMarkdown(text?) | Strips Markdown syntax (links, images, emphasis, code, headings, lists) for plain-text Schema.org fields. |
normalizeSchemaImage(src?) | Ensures relative image paths start with / while preserving absolute URLs. |
buildBrandSiteConfigFallback(brand?) | Converts nuxtify.brand into a low-priority (_priority: -10) site-config-stack entry with Organization identity. |
mergeSchemaOrgNodes(override, defaultNodes, breadcrumbNode?) | Honors frontmatter schemaOrg overrides while appending a BreadcrumbList node when none is present. |
countDocumentWords(body) | Counts words across a Nuxt Content AST body for reading time and Schema.org wordCount. |
buildContentPageSchemaNodes(docRef, options?, resolvers?) | Builds WebPage + optional BreadcrumbList JSON-LD nodes. |
buildArticleSchemaNodes(options, resolvers?) | Builds Article/BlogPosting + Person author + optional BreadcrumbList nodes. |
buildDocSchemaNodes(options, resolvers?) | Builds TechArticle + optional BreadcrumbList nodes for documentation pages. |
buildFaqSchemaNodes(questions?, resolvers?) | Builds FAQPage + Question JSON-LD nodes (used by PageFaq). |
buildArticleSeoMeta(doc, options?) | Produces useSeoMeta-compatible Open Graph article tags (ogType: 'article', articlePublishedTime, articleModifiedTime, articleTag, ogImage fallback) while preserving frontmatter seo overrides. |