A comprehensive TypeScript ecosystem for working with HL7 FHIR R4 resources. Whether you're building healthcare applications, integrating with EHR systems, or creating FHIR-compliant APIs, this monorepo provides everything you need with bulletproof type safety and runtime validation.
This project provides two complementary packages that work together to make FHIR development simple and type-safe:
Use FHIR types and validation in your own applications, whether you're building client apps, custom servers, or data processing pipelines.
Quickly build FHIR-compliant REST APIs with Express.js middleware that handles routing, validation, and capability statements automatically.
- π Complete Type Safety: Full TypeScript definitions for all FHIR R4 resources
- β Runtime Validation: Zod-powered schemas catch errors before they cause problems
- π Express Integration: Ready-to-use middleware for building FHIR servers
- π Comprehensive Coverage: Support for all 150+ FHIR R4 resource types
- π³ Tree Shakeable: Only bundle what you use
- β‘ Auto-Generated: Always up-to-date with official FHIR specifications
- ποΈ Builder Pattern: Intuitive APIs for defining FHIR capabilities
- βοΈ Modern Deployment: Built for serverless environments (AWS Lambda, Vercel) and traditional servers
Our comprehensive benchmarking shows excellent performance characteristics:
| Metric | @solarahealth/fhir-r4 | vs @ahryman40k/ts-fhir-types |
|---|---|---|
| Parsing Throughput | 46,445 patients/sec | 33% faster alternative |
| Bundle Size (Minified) | 235.81 KB | 81.9% smaller |
| Bundle Size (Gzipped) | 46.63 KB | 77.1% smaller |
| Cold-Start Time | 286.05ms | 12.3% faster |
| Memory Usage | 390 bytes/patient | Same efficiency |
| Validation Success | 100% | Same reliability |
Key Takeaway: Excellent performance with significantly smaller bundle sizes and faster cold-starts - ideal for both client-side applications and serverless deployments while maintaining strong server-side performance.
π Full benchmarking details: See benchmarking/fhir-r4/BENCHMARKING_SUMMARY.md for comprehensive performance analysis and recommendations.
Core FHIR R4 types and validation schemas
Perfect for developers who want to work with FHIR data in their applications, validate resources, or build custom FHIR solutions.
npm install @solarahealth/fhir-r4Use Cases:
- Validating FHIR resources in your application
- Type-safe FHIR data manipulation
- Building custom FHIR clients or processors
- Integrating with existing FHIR systems
Key Features:
- TypeScript type definitions for all FHIR R4 resources
- Zod schemas for runtime validation
- Support for both CommonJS and ES modules
- Tree-shakeable exports
π View detailed documentation β
Express.js middleware for building FHIR REST APIs
Perfect for developers who want to quickly expose their healthcare data through a FHIR-compliant REST API with modern deployment capabilities.
npm install @solarahealth/fhir-r4-server @solarahealth/fhir-r4 expressUse Cases:
- Building FHIR-compliant REST APIs
- Exposing existing healthcare data via FHIR
- Creating FHIR facades for legacy systems
- Rapid prototyping of FHIR servers
- Serverless FHIR API deployment
Key Features:
- Express middleware with builder pattern
- Auto-generated capability statements
- Built-in request/response validation
- Flexible data access layer (bring your own database)
- FHIR R4 REST API compliance
- Modern deployment support (AWS Lambda, Vercel, etc.)
π View detailed documentation β
import {
createPatientSchema,
createObservationSchema,
type Patient,
type Observation,
} from '@solarahealth/fhir-r4';
// Create a patient resource with type safety
const patient: Patient = {
resourceType: 'Patient',
id: 'patient-123',
active: true,
name: [{ family: 'Doe', given: ['John'] }],
gender: 'male',
birthDate: '1990-01-01',
};
// Validate the patient resource
const patientSchema = createPatientSchema();
const result = patientSchema.safeParse(patient);
if (result.success) {
console.log('β
Valid patient resource:', result.data);
} else {
console.error('β Validation errors:', result.error.issues);
}import express from 'express';
import type { Patient } from '@solarahealth/fhir-r4';
import { RestServer, builder, errors } from '@solarahealth/fhir-r4-server';
import { z } from 'zod';
const app = express();
app.use(express.json());
// Your data store (could be any database)
const patients: Record<string, Patient> = {
'123': {
resourceType: 'Patient',
id: '123',
name: [{ given: ['John'], family: 'Doe' }],
},
};
// Define Patient resource with read capability
const patientResource = builder
.defineResource('Patient')
.read((builder) =>
builder.id(z.string()).retrieveWith(async (id) => {
const patient = patients[id];
if (!patient) {
throw new errors.ResourceNotFound('Patient', id);
}
return patient;
}),
)
.build();
// Initialize FHIR server
const fhirServer = RestServer.init({
capabilities: {
resourceType: 'CapabilityStatement',
status: 'active',
date: new Date().toISOString(),
kind: 'instance',
fhirVersion: '4.0.1',
format: ['json'],
rest: [{ mode: 'server', resource: [patientResource] }],
},
});
// Mount FHIR middleware
app.use(
'/fhir',
RestServer.expressMiddleware(fhirServer, {
context: async () => ({}),
}),
);
app.listen(3000, () => {
console.log('π₯ FHIR server running on http://localhost:3000/fhir');
});Scenario: You're building a healthcare app, need to validate FHIR resources, or want to work with FHIR data in your existing application.
β Start with @solarahealth/fhir-r4 for types and validation
Examples: Client applications, data processors, FHIR validators, integration utilities
Scenario: You need to expose healthcare data through a FHIR-compliant REST API, either from scratch or as a facade over existing systems.
β Use both packages: @solarahealth/fhir-r4-server + @solarahealth/fhir-r4
Examples: FHIR servers, API gateways, healthcare data APIs, legacy system facades
Scenario: You need to consume data from FHIR APIs, validate incoming FHIR resources, or build FHIR-compatible clients.
β Start with @solarahealth/fhir-r4 for client-side validation and types
Examples: EHR integrations, FHIR clients, data synchronization tools
Scenario: You have existing healthcare data in non-FHIR formats and want to expose it through a modern FHIR REST API.
β Use @solarahealth/fhir-r4-server to create a FHIR facade with your data mapping logic
Examples: Legacy database APIs, HL7 v2 to FHIR converters, proprietary format bridges
import {
createObservationSchema,
createBundleSchema,
type Observation,
type Bundle,
} from '@solarahealth/fhir-r4';
const observation: Observation = {
resourceType: 'Observation',
id: 'obs-123',
status: 'final',
code: {
coding: [
{
system: 'http://loinc.org',
code: '29463-7',
display: 'Body Weight',
},
],
},
subject: { reference: 'Patient/patient-123' },
valueQuantity: {
value: 70,
unit: 'kg',
system: 'http://unitsofmeasure.org',
code: 'kg',
},
};
// Bundle multiple resources
const bundle: Bundle = {
resourceType: 'Bundle',
id: 'bundle-123',
type: 'collection',
entry: [{ resource: patient }, { resource: observation }],
};import { builder } from '@solarahealth/fhir-r4-server';
import { z } from 'zod';
const patientResource = builder
.defineResource('Patient')
.read((builder) =>
builder.id(z.string()).retrieveWith(async (id, context) => {
return await context.database.findPatient(id);
}),
)
.searchParams([
{
name: 'name',
type: 'string',
},
])
.search((builder) =>
builder
.params(
z.object({
name: z.string().optional(),
}),
)
.list(async (params, context, req) => {
const results = await context.database.searchPatients(params);
return {
resourceType: 'Bundle',
type: 'searchset',
entry: results.map((resource) => ({ resource })),
};
}),
)
.build();- Node.js (v16 or higher)
- npm
-
Clone the repository:
git clone <repository-url> cd fhir
-
Install dependencies:
npm install
-
Build all packages:
npm run build
cd packages/fhir-r4
npm run ci # Run full CI pipelineRegenerating Types and Schemas:
The types and schemas are auto-generated from the official FHIR specifications:
npm run generate # Download specs and regenerate everything
npm run test # Verify everything workscd packages/fhir-r4-server
npm run ci # Run full CI pipelinenpm run build- Build all packagesnpm run test- Run tests for all packagesnpm run clean- Clean build artifactsnpm run publish- Publish packages (requires proper permissions)
npm run build- Build the package (both CJS and ESM)npm run test- Run Jest testsnpm run typecheck- TypeScript type checkingnpm run lint- ESLint code lintingnpm run generate- Download specs and regenerate typesnpm run ci- Run full CI pipelinenpm run clean- Remove build artifacts
npm run build- Build the packagenpm run test- Run Jest testsnpm run typecheck- TypeScript type checkingnpm run lint- ESLint code lintingnpm run ci- Run full CI pipelinenpm run clean- Remove build artifacts
Complete support for all FHIR R4 resources, including:
- Administrative: Patient, Practitioner, Organization, Location, etc.
- Clinical: Observation, Condition, Procedure, DiagnosticReport, etc.
- Financial: Claim, Coverage, ExplanationOfBenefit, etc.
- Workflow: Task, Appointment, Schedule, etc.
- Infrastructure: Bundle, CapabilityStatement, OperationDefinition, etc.
Each FHIR resource has a corresponding schema creation function:
import {
createPatientSchema,
createObservationSchema,
createBundleSchema,
// ... and many more
} from '@solarahealth/fhir-r4';All FHIR resources are available as TypeScript types:
import type {
Patient,
Observation,
Bundle,
// ... and many more
} from '@solarahealth/fhir-r4';RestServer: Main server class for initializing FHIR serversbuilder: Fluent API for defining resource capabilitieserrors: FHIR-compliant error classes
import { builder } from '@solarahealth/fhir-r4-server';
const resource = builder
.defineResource('Patient')
.read(/* read handler */)
.search(/* search handler */)
.build();import { errors } from '@solarahealth/fhir-r4-server';
throw new errors.ResourceNotFound('Patient', '123');
throw new errors.BadRequest('Invalid parameter');- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Run tests:
npm run ci - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
The types and schemas are automatically generated from the official FHIR specifications. If you need to modify the generation process, edit the files in packages/fhir-r4/scripts/generate/R4/.
This project is licensed under the MIT License - see the LICENSE file for details.
- HL7 FHIR R4 Specification - Official FHIR R4 documentation
- FHIR R4 Resource Index - Complete list of FHIR R4 resources
- US Core Implementation Guide - US-specific FHIR profiles
- Zod Documentation - Runtime validation library used in our packages
- TypeScript Documentation - TypeScript language reference
- Express.js Documentation - Express web framework for Node.js
If you encounter any issues or have questions:
- Check the existing issues
- Search the package-specific documentation for your use case
- Create a new issue with a detailed description
- Include code examples and error messages when applicable
For @solarahealth/fhir-r4 (types and validation):
- π Complete documentation
- Common issues: Schema validation, TypeScript compilation, import/export problems
For @solarahealth/fhir-r4-server (REST API middleware):
- π Complete documentation
- Common issues: Express integration, resource handlers, deployment configurations
When reporting issues, please specify:
- Which package you're using (
@solarahealth/fhir-r4or@solarahealth/fhir-r4-server) - Your Node.js and TypeScript versions
- Minimal code example that reproduces the issue
- Expected vs actual behavior
@solarahealth/fhir-r4: See packages/fhir-r4/README.md@solarahealth/fhir-r4-server: See packages/fhir-r4-server/README.md
Built with β€οΈ by Solara Health Pty Ltd in Melbourne, Australia