npm package: @rxbenefits/mfe-config
Description: Configuration utilities for RxBenefits Micro Frontend applications - cookie isolation, environment helpers, and Auth0 setup
Author: RxBenefits
Latest version: 1.0.2

# @rxbenefits/mfe-config

Configuration utilities for RxBenefits Micro Frontend applications. Solves common MFE challenges including cookie isolation, environment configuration, and Auth0 setup.

## Installation

```bash
npm install @rxbenefits/mfe-config
```

## Features

- **Cookie Isolation**: Prevent 431 Request Header Too Large errors in local development
- **Environment Helpers**: Clean and parse environment variables reliably
- **Auth0 Utilities**: Simplified Auth0 configuration and session management
- **TypeScript**: Full type definitions included

## Quick Start

### Cookie Isolation Setup

When running multiple Next.js apps on localhost (e.g., shell on port 3000, MFE on port 3001), browsers share cookies across ports, causing header size limits to be exceeded. This library provides utilities to use 127.0.0.1 for API calls, which browsers treat as a separate domain from localhost.

```typescript
import { getMfeApiOrigin, buildMfeApiUrl } from '@rxbenefits/mfe-config';

// Get the API origin for your MFE
const apiOrigin = getMfeApiOrigin(3001); // Returns 'http://127.0.0.1:3001' in integrated mode

// Build full API URLs
const url = buildMfeApiUrl('/api/ben-admin/organizations', 3001);
// Returns: 'http://127.0.0.1:3001/api/ben-admin/organizations'
```

### Environment Variable Helpers

```typescript
import {
  cleanEnvValue,
  parseBooleanEnv,
  getEnvWithFallback,
} from '@rxbenefits/mfe-config';

// Remove quotes from env vars (Next.js includes them)
const apiUrl = cleanEnvValue(process.env.API_URL);

// Parse boolean values
const isEnabled = parseBooleanEnv(process.env.FEATURE_ENABLED, false);

// Try multiple env var names
const namespace = getEnvWithFallback(
  ['AUTH0_NAMESPACE', 'AUTH0_NAMESPACE_KEY'],
  'https://default.example.com'
);
```

### Auth0 Configuration

```typescript
import {
  loadAuth0Config,
  getAuth0SessionName,
  extractCustomClaims,
} from '@rxbenefits/mfe-config';

// Load Auth0 config from environment
const auth0Config = loadAuth0Config();

// Get recommended session cookie name
const sessionName = getAuth0SessionName('ben-admin');
// Returns: 'ben_admin_mfe_session'

// Extract custom claims from access token
const claims = extractCustomClaims(accessToken);
```

### Generate Recommended Environment Variables

```typescript
import { getRecommendedEnvVars } from '@rxbenefits/mfe-config';

const envVars = getRecommendedEnvVars({
  mfeName: 'ben-admin',
  mfePort: 3001,
  shellUrl: 'http://localhost:3000',
  auth0: {
    issuerBaseUrl: 'https://your-tenant.auth0.com',
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
    baseUrl: 'http://localhost:3001',
  },
});

// Returns object with all recommended env vars:
// {
//   NEXT_PUBLIC_SHELL_URL: 'http://localhost:3000',
//   NEXT_PUBLIC_MFE_API_ORIGIN: 'http://127.0.0.1:3001',
//   NODE_OPTIONS: '--max-old-space-size=4096 --max-http-header-size=32768',
//   AUTH0_SESSION_NAME: 'ben_admin_mfe_session',
//   AUTH0_SESSION_STORE_ID_TOKEN: 'false',
//   // ... etc
// }
```

## API Reference

### Cookie Isolation

#### `detectMfeEnvironment(): MfeEnvironment`

Detects the current MFE environment (browser, development, integrated).

#### `getMfeApiOrigin(mfePort?, envVarName?): string`

Gets the API origin URL. Returns 127.0.0.1 in integrated dev mode to avoid cookie collisions.

#### `buildMfeApiUrl(endpoint, mfePort?): string`

Builds a full URL for an API endpoint with proper origin.

#### `getAuth0SessionName(mfeName): string`

Generates a unique session cookie name to avoid collisions.

#### `getNodeOptions(maxOldSpaceSize?, maxHeaderSize?): string`

Generates NODE_OPTIONS string with increased header size limit.

#### `getRecommendedEnvVars(config): Record<string, string>`

Generates all recommended environment variables for MFE setup.

### Environment Helpers

#### `cleanEnvValue(value): string`

Removes quotes and trims environment variable values.

#### `normalizeOrigin(value): string`

Removes trailing slashes from URLs.

#### `parseBooleanEnv(value, defaultValue?): boolean`

Parses boolean environment variables.

#### `parseNumberEnv(value, defaultValue): number`

Parses numeric environment variables.

#### `getEnvWithFallback(keys, defaultValue?): string`

Tries multiple env var names until one is found.

#### `validateRequiredEnv(requiredVars): void`

Validates that required environment variables are set.

### Auth0 Helpers

#### `getAuth0Namespace(): string`

Gets Auth0 claims namespace from environment.

#### `getAuth0ManagementAudience(): string | null`

Gets Auth0 Management API audience URL.

#### `getAuth0Audience(options?): string | null`

Resolves the preferred API audience using `AUTH0_API_AUDIENCE` / `AUTH0_AUDIENCE`, falling back to the configured namespace (or the default namespace) and finally the Management API when permitted.

#### `getAuth0Scope(): string`

Gets Auth0 scope from environment.

#### `loadAuth0Config(): MfeAuth0Config`

Loads complete Auth0 configuration from environment.

#### `extractCustomClaims(accessToken, namespace?): Record<string, any> | null`

Extracts custom claims from JWT access token.

#### `getMinimalSessionUser(accessToken, namespace?): { userId?: string }`

Extracts minimal user data for session storage (reduces cookie size).

## Common Issues Solved

### 431 Request Header Fields Too Large

**Problem**: Multiple MFEs on localhost share cookies, causing combined header size to exceed limits.

**Solution**: Use 127.0.0.1 for API calls in integrated mode.

```typescript
// In .env.local
NEXT_PUBLIC_MFE_API_ORIGIN=http://127.0.0.1:3001

// In your API client
import { getMfeApiOrigin } from '@rxbenefits/mfe-config';
const apiUrl = getMfeApiOrigin(3001);
```

### Large Auth0 Session Cookies

**Problem**: Auth0 sessions store access tokens, ID tokens, and custom claims, causing large cookies.

**Solution**: Minimize session data and don't store ID token.

```typescript
// In .env.local
AUTH0_SESSION_STORE_ID_TOKEN=false

// In your Auth0 callback
import { getMinimalSessionUser } from '@rxbenefits/mfe-config';
const minimalUser = getMinimalSessionUser(accessToken);
// Only stores userId, not full user profile
```

### Environment Variable Quoting

**Problem**: Next.js includes quotes from .env files in variable values.

**Solution**: Use `cleanEnvValue` to remove quotes.

```typescript
import { cleanEnvValue } from '@rxbenefits/mfe-config';
const url = cleanEnvValue(process.env.API_URL);
```

## TypeScript

This package is written in TypeScript and includes complete type definitions.

```typescript
import type {
  MfeConfig,
  MfeAuth0Config,
  MfeEnvironment,
} from '@rxbenefits/mfe-config';
```

## License

MIT © RxBenefits