Hosted Components LogoHosted-Components

Utility Functions

Utility functions for the Hosted Components Service

Utility Functions

This page documents the various utility functions available in the library.

Tailwind Utilities

cn

A utility function that combines clsx and tailwind-merge for handling Tailwind CSS class names.

import { cn } from '@/lib/utils';

// Usage
cn('base-class', condition && 'conditional-class', 'another-class');

Format Utilities

Card Number Formatting

import { formatCardNumber, unformatCardNumber } from '@/lib/utils';

// Format card number with spaces every 4 digits
formatCardNumber('4111111111111111'); // "4111 1111 1111 1111"

// Remove spaces from card number
unformatCardNumber('4111 1111 1111 1111'); // "4111111111111111"

Expiry Date Formatting

import { formatExpiryDate, unformatExpiryDate } from '@/lib/utils';

// Format expiry date with slash
formatExpiryDate('1223'); // "12 / 23"

// Remove formatting from expiry date
unformatExpiryDate('12 / 23'); // "12/23"

CSS Class Validation

validateClasses

Validates CSS class configurations against predefined rules.

import { validateClasses } from '@/lib/utils';

const classes = {
	button: { 'background-color': 'blue' },
	'button:hover': { 'background-color': 'darkblue' },
};
const validatedClasses = validateClasses(classes);

convertToCssString

Converts validated class rules into a CSS string.

import { convertToCssString } from '@/lib/utils';

const cssString = convertToCssString(validatedClasses);

Font Family Handler

import { handleFontFamily } from '@/lib/utils';

handleFontFamily('Roboto', (fontFamily) => {
	// Handles loading Google Fonts and provides fallback
	console.log(fontFamily); // "'Roboto', Arial, Helvetica, sans-serif"
});

CSS Variables Validation

import { validateCSSVariables } from '@/lib/utils';

const variables = {
	'--primary-color': '#007bff',
	'--font-size': '16px',
};
const validatedVars = validateCSSVariables(variables);

Environment Utilities

devOnly

A utility function that redirects to the home page if the application is running in production mode.

import { devOnly } from '@/lib/utils';

// Usage in development-only routes
devOnly(); // Redirects to "/" if NODE_ENV is "production"

Token Utilities

validateJWTToken

Validates JWT tokens by checking their format and expiration.

import { validateJWTToken } from '@/lib/utils';

const isValid = validateJWTToken('your.jwt.token');

The function performs the following checks:

  • Verifies the token has three parts separated by dots
  • Validates base64url format for each part
  • Checks token expiration if present
  • Returns true if the token is valid, false otherwise

Server Actions

Server Actions are async functions that are executed on the server-side. These functions can be used in both client and server components, and are specifically designed for creating, updating, or deleting data. For more information, see Next.js Server Actions documentation.

createCardToken

A server action function for creating a payment method token for card payments.

import { createCardToken } from '@/lib/utils';

// Usage
const response = await createCardToken(token, {
	countryCode: 'US',
	accountNumber: '4111111111111111',
	expiryDate: '12/25',
	accountHolderName: 'John Doe',
	termAndConditionAgreed: true,
});

API Utilities

apiRequest

A type-safe utility function for making HTTP requests with built-in error handling and response formatting.

import { apiRequest } from '@/lib/utils';

// Example GET request
const response = await apiRequest({
	url: 'https://api.example.com/data',
	method: 'GET',
	token: 'your-auth-token', // Optional
});

// Example POST request with body
const response = await apiRequest({
	url: 'https://api.example.com/data',
	method: 'POST',
	token: 'your-auth-token',
	body: { key: 'value' },
});

// Type-safe response handling
interface UserData {
	id: string;
	name: string;
}

const response = await apiRequest<UserData>({
	url: 'https://api.example.com/user',
	method: 'GET',
});
// response.data will be typed as UserData | null

The function handles:

  • Automatic JSON parsing
  • Error handling with detailed error information
  • Authentication via Bearer token
  • Type-safe responses
  • Proper error logging with context

Logging Utilities

DatadogLogger

The DatadogLogger utility provides structured logging with Datadog-compatible format for server-side operations.

Basic Usage

import { DatadogLogger } from '@/lib/utils/datadog-logger';

// Info logging
DatadogLogger.info('Operation completed successfully', {
	operationType: 'payment_creation',
	duration: 1250,
	merchantId: 'merchant-123',
});

// Warning logging
DatadogLogger.warn('Rate limit approaching', {
	currentRequests: 95,
	limit: 100,
	timeWindow: '1m',
});

// Error logging - message only
DatadogLogger.error('Payment validation failed');

// Error logging - with error object
DatadogLogger.error('Database connection failed', error);

// Error logging - with error and additional context
DatadogLogger.error('Payment processing failed', error, {
	paymentId: 'payment-456',
	merchantId: 'merchant-123',
	attemptNumber: 3,
});

Method Signatures

// Info logging
static info(message: string, additionalData?: Record<string, unknown>): void

// Warning logging
static warn(message: string, additionalData?: Record<string, unknown>): void

// Error logging
static error(
  message: string,
  error?: Error | unknown,
  additionalData?: Record<string, unknown>
): void

// Debug logging (only in non-production)
static debug(message: string, additionalData?: Record<string, unknown>): void

Important Notes

  • Error Parameter: The second parameter of error() should be an Error object or the actual error, not additional data
  • Additional Data: Use the third parameter for additional context data
  • Production Safety: Debug logs are automatically filtered out in production
  • Sensitive Data: Use logSensitiveData() for development-only sensitive information logging

Common Patterns

// ✅ Correct usage patterns
DatadogLogger.info('User authenticated successfully', { userId: 'user-123' });
DatadogLogger.error('Authentication failed');
DatadogLogger.error('Database query failed', dbError);
DatadogLogger.error('API request failed', apiError, { endpoint: '/api/payments' });

// ❌ Incorrect usage patterns
// Don't pass empty object as second parameter
DatadogLogger.error('Validation failed', {}); // Wrong!

// Don't pass additional data as second parameter
DatadogLogger.error('Process failed', { step: 'validation' }); // Wrong!

Specialized Logging Methods

// API request logging
DatadogLogger.apiRequest('Payment API called', {
	endpoint: '/api/payments',
	method: 'POST',
	statusCode: 200,
});

// Database operation logging
DatadogLogger.database('User record created', {
	table: 'users',
	operation: 'INSERT',
	recordId: 'user-123',
});

// Sensitive data logging (dev/staging only)
DatadogLogger.logSensitiveData('Payment details', {
	cardNumber: '4111111111111111',
	expiryDate: '12/25',
});