Medplum Client in NestJS App
# support
t
Hi everyone πŸ‘‹ We found an unexpected behavior when using MedplumClient on our backend (NestJS) for patient self-registration. βΈ» πŸ” Issue We use a singleton MedplumClient:
Copy code
const client = new MedplumClient({
  baseUrl,
  clientId,
  clientSecret,
});
Our account creation flow is as follow, from our NestJS app: 1. POST /auth/newuser to Medplum 2. POST /auth/newpatient to Medplum 3. POST /oauth2/token (manual HTTP call) to Medplum 4. client.readResource('Patient', ...) 5. client.updateResource(...) πŸ‘‰ The first time the flow runs: everything works. πŸ‘‰ The second time: /auth/newuser creates the User in the wrong project (Super Admin project instead of the clientApplication project). βΈ» 🧠 Root cause We discovered that:
Copy code
await client.readResource('Patient', id);
implicitly authenticates the MedplumClient using client_credentials. After this call, client.sessionDetails is populated with a ClientApplication session.
Copy code
"sessionDetails":
    {
        "project":
        {
            "resourceType": "*",
            "id": "****",
            "name": "*"
        },
        "membership":
        {
            "resourceType": "ProjectMembership",
            "id": "****",
            "user": {...}
            "profile":
            {
...
            },
            "admin": true
        },
From then on, /auth/newuser is no longer anonymous and behaves differently β†’ Users get created in the wrong project (whereas session details shows that the session is linked to another project. ❓ Questions What Is the recommended pattern: β€’ Create one new client per HTTP request instead of having a singleton in the service ? βœ”οΈ Workaround
Copy code
this.medplum.clear();
reinitialisation works Thanks for your help.
m
Hi @thomabig ! Is this client id and secret tied to the super admin account? I believe what is happening is that the server respects the authenticated context even for endpoints that don't require it (newuser), which is why medplum.clear() is able to resolve the issue
48 Views