Tutorial: Configuring Digital E-Prescriptions in a Clinic System: FHIR R4 Integration
N
Back to Blog

Tutorial: Configuring Digital E-Prescriptions in a Clinic System: FHIR R4 Integration

Tutorial
Nugroho Setiawan · Konsultan IT & Full Stack Developer 05 May 2026 10 min baca 2,911 kata 568 views
This article guides you through configuring digital e-prescriptions in a clinic system, from basic concepts to technical implementation. Learn about integration with the FHIR R4 standard for operational efficiency and SatuSehat compliance.

Implementing a digital e-prescription system is no longer an option, but an urgent necessity for healthcare facilities in Indonesia, especially clinics. With the demands for operational efficiency, data accuracy, and compliance with regulations such as the Minister of Health Regulation (PMK) No. 14 of 2021 concerning Standards for Business Activities and Products in the Implementation of Risk-Based Business Licensing in the Health Sector, and PMK No. 24 of 2022 concerning Medical Records, clinics are faced with the challenge of transforming a manual prescription process that is error-prone and time-consuming. The manual prescription process, which involves handwriting, often leads to misinterpretation by pharmacists, prescription duplication, and even potential drug abuse. Statistics show that prescription errors account for around 10-20% of total medical errors occurring in healthcare facilities, with 7% of them potentially causing serious impacts on patients. This article will guide you comprehensively, step by step, in configuring a digital e-prescription system in your clinic, with a focus on technical implementation using the FHIR R4 standard for seamless integration. We will discuss basic concepts, implementation details, runnable code examples, data payload structures, as well as best practices and FAQs to ensure your system not only functions but is also optimal, secure, and future-ready.

Basic Concepts of E-Prescription and FHIR Interoperability

A digital e-prescription is an electronic drug prescribing system that allows doctors to write, send, and monitor drug prescriptions through software. Its main benefits include increased prescribing accuracy through automatic validation, reduced risk of prescription misreading errors, time efficiency, and ease of access and tracking of patient prescription history. In Indonesia, the legal basis for e-prescription implementation is increasingly strengthened by PMK No. 24 of 2022, which requires healthcare facilities to maintain electronic medical records, including a prescribing module. Furthermore, the SatuSehat digital health transformation program from the Ministry of Health of the Republic of Indonesia demands interoperability of health data between healthcare facilities, and e-prescription becomes one of the crucial pillars in this medical information exchange.

To achieve effective interoperability, Fast Healthcare Interoperability Resources (FHIR) R4 is the standard of choice adopted globally and also in Indonesia through the SatuSehat platform. FHIR is a health data exchange standard developed by Health Level Seven International (HL7), designed to facilitate efficient and secure exchange of health information. FHIR R4 (Release 4) is the latest stable version that is widely used. In the context of e-prescription, several relevant FHIR resources include: MedicationRequest, which represents a drug prescription request by a doctor; Patient, for patient identity information; Practitioner, for doctor identity information; and Organization, for healthcare facility or pharmacy information. The use of this standard ensures that e-prescription data can be understood and processed by other systems that also implement FHIR, such as pharmacy systems or the SatuSehat platform itself.

For example, when a doctor creates an e-prescription, the clinic system will create an instance of the MedicationRequest resource. This resource will include details such as the prescribed drug (medicationCodeableConcept or medicationReference), dosage instructions (dosageInstruction), patient information (subject), prescribing doctor (requester), prescribing date (authoredOn), and prescription status (status such as 'active', 'completed', 'cancelled'). This data can then be sent to the destination pharmacy or the SatuSehat platform in JSON or XML format according to the FHIR standard. An in-depth understanding of the structure of these FHIR resources is essential to ensure that the transmitted data is valid and can be correctly processed by the receiving system.

It is important to note that validation and authentication in the e-prescription process must meet the highest security standards. Every digital prescription must have a valid electronic signature from an authorized doctor, in accordance with applicable regulations. This not only guarantees the authenticity of the prescription but also accountability. Integration with third-party electronic signature service providers is often necessary to meet these requirements. In addition, the system must ensure that only authorized pharmacies can access and fulfill the prescription, usually through an authorization mechanism based on API Key or OAuth 2.0.

Technical Implementation Details of the E-Prescription System

Implementing a robust digital e-prescription system requires a well-planned architecture. Generally, this architecture consists of several main components: a user interface (frontend) for doctors, a backend API service to manage data and business logic, a database for storing prescription data, and an integration layer to communicate with external systems such as pharmacies or SatuSehat. For the backend, we recommend using Laravel 11.x, a powerful PHP framework with a mature ecosystem for RESTful API development. Laravel provides features such as ORM (Eloquent), middleware for authentication/authorization, and queues for asynchronous processing that are very useful in integration.

As a database, PostgreSQL 16 is an excellent choice because it is known for its reliability, scalability, and its JSONB capabilities that support storing semi-structured data such as FHIR resources efficiently. The database schema will include tables for patients, doctors, medications, and of course, the prescription itself, which may store part of the FHIR payload directly or a reference to object storage. For the FHIR integration layer, we can use the HAPI FHIR 6.8 library (for Java) or implement a custom FHIR client using a language such as PHP with the Guzzle HTTP client or Node.js with axios. HAPI FHIR provides a comprehensive parser, validator, and RESTful client for interacting with a FHIR server.

The prescribing process will start from the doctor's interface, where they select a patient, search for a medication from the formulary list, and determine the dose, frequency, and duration. This data is then sent to the Laravel backend. The backend will validate the input, create a FHIR MedicationRequest instance, and store it in PostgreSQL. After being successfully saved, the backend will send this FHIR payload to the SatuSehat API endpoint or directly to the integrated pharmacy system. For sending to SatuSehat, make sure you use the MedicationRequest endpoint that complies with the SatuSehat FHIR R4 specification and authenticate using an OAuth 2.0 token obtained from the SatuSehat authorization service.

It is important to pay attention to the version of the standard used. SatuSehat currently implements FHIR R4. Make sure the libraries and payload structures you use are fully compatible with this specification. For example, to identify medications, you need to use a standard coding system such as SNOMED CT or LOINC if available, in accordance with SatuSehat requirements. Handling prescription status is also crucial: from 'draft' when the doctor is preparing it, 'active' after it is approved and sent, to 'completed' after the medication is taken by the patient, or 'cancelled' if it is canceled. Every status transition must be reflected in the system and communicated to the relevant parties.

For cases where the clinic has an internal pharmacy system, integration can be done directly without going through SatuSehat, although it is recommended to still send to SatuSehat for the purpose of nationally integrated medical records. If integrating directly, the pharmacy API must be able to receive and process the FHIR MedicationRequest payload. The use of Node.js 20 LTS with a framework such as Express.js is often chosen to build a dedicated integration microservice because of its good performance in I/O-bound operations and its rich library ecosystem for JSON parsing.

Example of FHIR E-Prescription Implementation Code

This section will show relevant code examples for implementing e-prescriptions using Laravel (PHP) for the backend and Node.js for simulating sending to a FHIR/SatuSehat server. This code will demonstrate how a FHIR MedicationRequest resource can be built and sent.

Example 1: Creating a MedicationRequest Payload in Laravel (PHP)

This is a simple example of how you can build a data array representing a FHIR MedicationRequest resource in a Laravel Controller, before converting it to JSON and sending it. Assume you have patient, doctor, and medication data from the form input.

<?php namespace App\'Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; class EResepController extends Controller { public function storeMedicationRequest(Request $request) { $validatedData = $request->validate([ 'patient_id' => 'required|string', 'practitioner_id' => 'required|string', 'medication_code' => 'required|string', 'medication_display' => 'required|string', 'dosage_text' => 'required|string', 'route_code' => 'required|string', 'route_display' => 'required|string', 'period_unit' => 'required|string', 'period_value' => 'required|integer', 'day_of_week' => 'nullable|array', 'time_of_day' => 'nullable|array', 'as_needed_boolean' => 'boolean', 'quantity_value' => 'required|integer', 'quantity_unit' => 'required|string' ]); $fhirPayload = [ 'resourceType' => 'MedicationRequest', 'id' => (string) \Illuminate\Support\Str::uuid(), 'status' => 'active', 'intent' => 'order', 'medicationCodeableConcept' => [ 'coding' => [ [ 'system' => 'http://terminology.hl7.org/CodeSystem/v3-RXNORM', 'code' => $validatedData['medication_code'], 'display' => $validatedData['medication_display'] ] ], 'text' => $validatedData['medication_display'] ], 'subject' => [ 'reference' => 'Patient/' . $validatedData['patient_id'], 'display' => 'Nama Pasien Contoh' // Ambil dari database pasien ], 'requester' => [ 'reference' => 'Practitioner/' . $validatedData['practitioner_id'], 'display' => 'Nama Dokter Contoh' // Ambil dari database dokter ], 'authoredOn' => now()->toIso8601String(), 'dosageInstruction' => [ [ 'text' => $validatedData['dosage_text'], 'timing' => [ 'repeat' => [ 'boundsPeriod' => [ 'start' => now()->toIso8601String(), 'end' => now()->add($validatedData['period_value'], $validatedData['period_unit'])->toIso8601String() ], 'dayOfWeek' => $validatedData['day_of_week'], 'timeOfDay' => $validatedData['time_of_day'] ], 'code' => [ 'coding' => [ [ 'system' => 'http://terminology.hl7.org/CodeSystem/v3-TimingEvent', 'code' => 'QD', 'display' => 'Once a day' ] ] ] ], 'route' => [ 'coding' => [ [ 'system' => 'http://terminology.hl7.org/CodeSystem/v3-RouteOfAdministration', 'code' => $validatedData['route_code'], 'display' => $validatedData['route_display'] ] ], 'text' => $validatedData['route_display'] ], 'asNeededBoolean' => $validatedData['as_needed_boolean'] ?? false ] ], 'dispenseRequest' => [ 'quantity' => [ 'value' => $validatedData['quantity_value'], 'unit' => $validatedData['quantity_unit'] ] ] ]; // Simpan ke database Anda di sini (opsional, jika perlu menyimpan payload mentah) // Misalnya: EResep::create(['payload' => json_encode($fhirPayload)]); // Kirim ke server FHIR/SatuSehat try { $response = Http::withHeaders([ 'Authorization' => 'Bearer ' . $this->getSatuSehatAccessToken(), 'Content-Type' => 'application/json' ])->post('https://api-satusehat.kemkes.go.id/fhir-r4/v1/MedicationRequest', $fhirPayload); if ($response->successful()) { return response()->json(['message' => 'E-Resep berhasil dikirim.', 'data' => $response->json()], 200); } else { return response()->json(['message' => 'Gagal mengirim E-Resep.', 'errors' => $response->json()], $response->status()); } } catch (\Exception $e) { return response()->json(['message' => 'Terjadi kesalahan sistem: ' . $e->getMessage()], 500); } } private function getSatuSehatAccessToken() { // Implementasi untuk mendapatkan access token dari SatuSehat // Ini melibatkan permintaan POST ke endpoint OAuth SatuSehat dengan client_id, client_secret, grant_type 'client_credentials' // Simpan dan kelola token agar tidak sering request return 'YOUR_SATUSEHAT_ACCESS_TOKEN'; } }

The PHP code above shows how prescription data from the input is validated and then mapped into a JSON structure that conforms to the FHIR MedicationRequest R4. The subject and requester sections use references to the Patient and Practitioner resources that already exist in the FHIR system. The getSatuSehatAccessToken() function is a placeholder that you must implement to obtain an authorization token from SatuSehat. The submission is done using the Guzzle HTTP client integrated in Laravel.

Example 2: Sending a FHIR Payload to the FHIR/SatuSehat Server using Node.js

If you have a Node.js microservice for integration, here is an example of how you can send a ready-made FHIR payload to the SatuSehat endpoint.

// app.js or integrationService.js const express = require('express'); const axios = require('axios'); const app = express(); app.use(express.json()); // Middleware for parsing JSON const SATUSEHAT_BASE_URL = 'https://api-satusehat.kemkes.go.id/fhir-r4/v1'; const SATUSEHAT_AUTH_URL = 'https://api-satusehat.kemkes.go.id/oauth2/v1'; const CLIENT_ID = 'YOUR_SATUSEHAT_CLIENT_ID'; const CLIENT_SECRET = 'YOUR_SATUSEHAT_CLIENT_SECRET'; let accessToken = ''; let tokenExpiry = 0; async function getSatuSehatAccessToken() { if (accessToken && Date.now() < tokenExpiry) { return accessToken; } try { const response = await axios.post(`${SATUSEHAT_AUTH_URL}/accesstoken?grant_type=client_credentials`, null, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, params: { client_id: CLIENT_ID, client_secret: CLIENT_SECRET } }); accessToken = response.data.access_token; tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // Subtract 60 seconds for buffer return accessToken; } catch (error) { console.error('Error getting SatuSehat access token:', error.response ? error.response.data : error.message); throw new Error('Failed to obtain SatuSehat access token'); } } app.post('/api/send-eresep', async (req, res) => { const fhirMedicationRequestPayload = req.body; // FHIR payload from clinic frontend/backend if (!fhirMedicationRequestPayload || fhirMedicationRequestPayload.resourceType !== 'MedicationRequest') { return res.status(400).json({ message: 'Invalid FHIR MedicationRequest payload provided.' }); } try { const token = await getSatuSehatAccessToken(); const response = await axios.post(`${SATUSEHAT_BASE_URL}/MedicationRequest`, fhirMedicationRequestPayload, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }); res.status(200).json({ message: 'E-Prescription successfully sent to SatuSehat.', data: response.data }); } catch (error) { console.error('Error sending E-Prescription to SatuSehat:', error.response ? error.response.data : error.message); res.status(500).json({ message: 'Failed to send E-Prescription to SatuSehat.', errors: error.response ? error.response.data : error.message }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Integration service running on port ${PORT}`); });

This Node.js example shows how to create a simple Express server that receives a FHIR MedicationRequest payload, obtains an access token from SatuSehat (with a token caching mechanism), and then sends that payload to the SatuSehat FHIR endpoint. Be sure to replace CLIENT_ID and CLIENT_SECRET with your SatuSehat API credentials. Basic error handling is also included to provide informative feedback.

FHIR Payload Structure and Error Handling

Understanding the FHIR payload structure is key to implementing digital e-prescriptions. The following is a realistic example of a JSON payload for the MedicationRequest resource that complies with the FHIR R4 specification and SatuSehat requirements. This payload includes essential information such as patient, doctor, medication, dosage, and status.

The following is an example MedicationRequest payload ready to be sent to SatuSehat, complete with required elements such as resourceType, status, intent, subject, medicationCodeableConcept, and dosageInstruction:

{ "resourceType": "MedicationRequest", "identifier": [ { "system": "http://sys-ids.kemkes.go.id/prescription", "value": "RESEP-2024-0001" } ], "status": "active", "intent": "order", "category": [ { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/medicationrequest-category", "code": "outpatient", "display": "Outpatient" } ] } ], "medicationCodeableConcept": { "coding": [ { "system": "http://sys-ids.kemkes.go.id/kfa", "code": "93000123", "display": "Paracetamol 500 mg Tablet" } ] }, "subject": { "reference": "Patient/100000030009", "display": "Budi Santoso" }, "encounter": { "reference": "Encounter/100000040010" }, "authoredOn": "2024-05-20T10:00:00+07:00", "requester": { "reference": "Practitioner/100000050011", "display": "dr. Siti Aminah" }, "dosageInstruction": [ { "sequence": 1, "text": "3 times a day 1 tablet after meals", "timing": { "repeat": { "frequency": 3, "period": 1, "periodUnit": "d" } }, "route": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/v3-RouteOfAdministration", "code": "PO", "display": "Oral" } ] }, "doseAndRate": [ { "doseQuantity": { "value": 1, "unit": "Tablet", "system": "http://unitsofmeasure.org", "code": "TAB" } } ] } ] }

Note that every reference (Patient, Practitioner, Encounter) must use a valid ID that has already been synchronized with SatuSehat. For error handling, you are advised to check the HTTP status code: 400 usually indicates the payload does not conform to the schema, 401 means the token is expired or invalid, while 422 often appears because a reference was not found. Store response logs in a structured manner so that e-prescription audits are easier to perform.

Practical Tips for Implementing FHIR E-Prescriptions in Clinics

First, validate the payload before sending it. Use JSON Schema or a FHIR validator library such as fhir-validator to ensure that no required elements are missing. Perform validation on the clinic server side so that errors are detected earlier and do not burden the SatuSehat endpoint. In addition, implement a retry mechanism with exponential backoff to handle temporary network disruptions, but avoid resending without an idempotency key so that prescription duplication does not occur.

Second, manage access tokens correctly. SatuSehat tokens have a limited validity period, so token caching is very important. Store the token along with its expiration time in memory or Redis, and refresh it before it expires. Do not store CLIENT_SECRET in source code; use environment variables or a secret manager. For production environments, enable HTTPS and restrict access to the integration endpoint only from registered clinic IPs.

Third, prepare a fallback strategy. If sending to SatuSehat fails, store the prescription in a local queue (for example, an outbox table) and resend it periodically. Notify the pharmacy staff or doctor if repeated failures occur. That way, prescription services continue to run even if there are integration issues. Finally, test in the SatuSehat sandbox environment before go-live, and document every change to the FHIR version used.

FAQ

What is the difference between MedicationRequest and MedicationDispense?

MedicationRequest represents a doctor's request or prescription for medication, while MedicationDispense records the medication actually handed over by the pharmacist. In the e-prescription flow, the two complement each other: the prescription is created first, then the dispense is recorded after the medication is given to the patient.

What if the patient ID does not yet exist in SatuSehat?

You must ensure the patient data is already registered and has a valid SatuSehat ID. If not, synchronize or register the patient first via the Patient resource. Sending a MedicationRequest with an unknown patient reference will result in a validation error.

May access tokens be stored in a database?

Yes, but it is better to store them in temporary storage such as Redis with a clear expiration time. Avoid storing tokens in logs or files that can be accessed publicly. Also ensure the token refresh process runs automatically so it does not disrupt prescription delivery.

Must the payload use UTF-8 encoding?

Yes, use UTF-8 and set the header Content-Type: application/json. Ensure that special characters in drug names or dosage instructions do not cause encoding problems. Test with data containing non-ASCII characters to ensure the integration runs stably.

Conclusion

Integrating digital e-prescriptions with FHIR R4 in SatuSehat is not merely a technical obligation, but an opportunity to improve the accuracy, speed, and security of prescription services at your clinic. By understanding the payload structure, managing tokens properly, and preparing mature error handling and fallback, the e-prescription system can run reliably and in compliance with regulations. Start from the sandbox environment, test every scenario, then deploy gradually.

Need assistance in designing the integration architecture, validating payloads, or auditing your clinic's system readiness? Consult your clinic's digital e-prescription needs with our expert team to get a solution that is secure, efficient, and compliant with SatuSehat standards. Contact us now and realize a better digital transformation of healthcare services.

This article is part of the knowledge base of Nugroho Setiawan, an IT consultant in Jogja (Yogyakarta). Related solutions: Clinic Management System BPJS & SatuSehat Integration. Need a free consultation?

Terakhir diperbarui 18 Oct 2026

Komentar

Komentar ditinjau sebelum tampil.

Belum ada komentar. Jadilah yang pertama!

Butuh bantuan implementasi atau dashboard data?

Saya membantu konsultasi IT, pengembangan aplikasi, dan visualisasi data untuk rumah sakit, klinik, dan bisnis di Yogyakarta (DIY), Magelang, dan sekitarnya.

WhatsApp Jasa Visualisasi Data Demo VizStudio
Produk & Solusi SIMRS ERP Portfolio Konsultasi Gratis