Backend Setup
Before shipping your game, you must route NPC requests through your backend. This page explains why and how to configure the SDK.
Why You Need a Backend
During development, the SDK calls LoreMind directly using your Server API Key stored in Unity's per-project user settings (the UserSettings/ folder). This is convenient for prototyping but not safe for production.
The Problem with Direct Calls
If you ship a game that calls LoreMind directly:
- Your API key is in the build - Anyone can extract it
- No player identification - The API requires
playerIdfor rate limiting and memory - No custom rate limiting - Can't control per-player usage
- No audit trail - Can't track who's making requests
That's why the SDK doesn't allow it. DirectApiTransport and LoreService.SetServerMediatedAuth, which send a Server API Key, exist only in the Editor and in Dedicated Server builds (UNITY_SERVER). A game client build in EditorDirect transport mode fails with an explanation (a Dedicated Server build only warns). Game clients use Custom Backend or SetInCode.
The Backend Pattern
Instead, your game calls your backend, and your backend calls LoreMind:
flowchart LR
game["Your Game<br/><small>client</small>"]:::neutral --> backend["Your Backend<br/><small>adds API key</small>"]:::neutral --> api["LoreMind API"]:::runtime
classDef runtime fill:#d96a57,stroke:#a03f37,color:#2b0e0a
classDef neutral fill:transparent,stroke-dasharray:4 3
Your backend:
- Authenticates players: verifies the player's session token from your login (Steam, Epic, PlayFab, custom)
- Derives the player ID from that token, never from the request body
- Limits each player's requests: LoreMind's limits are per project, not per player
- Adds the API key, stored securely in environment variables
- Forwards to LoreMind and returns the response to your game
Before You Start
You need:
- A working NPC in the Editor - Complete Installation and Your First NPC first
- A game backend - PlayFab, Firebase, Nakama, or custom server
- Backend code that calls LoreMind - See Server Integration for examples
Configuring the SDK
Step 1: Set Up Your Backend Endpoint
Your backend needs an endpoint that:
- Receives NPC requests from your game (over HTTPS)
- Verifies the player's session token (see Sending the Player's Session Token)
- Adds your LoreMind API key and the player ID from the token
- Forwards to
https://loremind.peekgames.dev/api/loremind/v1/npc/interact, waiting up to 600 seconds - Returns LoreMind's response unchanged: its status code, JSON body, and
Retry-Afterheader
See Server Integration for complete backend examples (Nakama, PlayFab, Node.js, and Mirror with a C# service).
Step 2: Configure the SDK
- Open Window > LoreMind > Control Panel
- Set Transport Mode to Custom Backend
- Enter your Backend URL (e.g.,
https://api.yourgame.com/api/npc/interact) - Click Save
The SDK will now route all NPC requests to your backend instead of calling LoreMind directly.
The Backend URL receives your player's session token, so the SDK checks it:
- It must be
https, with no user name or password in it. - Plain
httpis accepted only forlocalhost, and only in the Editor and Development Builds. A release build with a non-https orlocalhostBackend URL fails. - Backslashes, spaces and control characters are refused.
A CustomBackendTransport with an unsafe URL is not ready (IsReady is false): its requests fail with CONFIG_ERROR and nothing is sent.
Step 3: Test in a Build
- Create a development build
- Run it and test NPC interactions
- Verify requests go through your backend (check server logs)
- Verify responses work correctly
Testing a Local Backend on a Phone
A Development Build accepts plain http only to localhost (the device itself). A LAN address of your computer, such as http://192.168.1.20:3000, is refused even in Development Builds.
- Android: connect the device over USB and run
adb reverse tcp:3000 tcp:3000(use your backend's port). Thenhttp://localhost:3000on the device reaches port 3000 on your computer, so set the Backend URL to that. Seereversein the adb documentation. - iOS, or without USB: expose your local backend through an
httpstunnel and use itshttpsURL.
What Your Backend Receives
The SDK sends this JSON to your backend:
{
"text": "Hello, what's your name?",
"entityMindId": "em_innkeeper_garrick",
"memory": { "retrieve": true },
"context": {
"location": "The Rusty Anvil Tavern",
"timeOfDay": "evening",
"nearbyCharacters": ["Mysterious stranger"]
},
"conversationHistory": [
{ "role": "user", "content": "Good evening." },
{ "role": "assistant", "content": "Evening, traveler. Ale or a room?" }
],
"activeKnowledgeTags": ["act1", "village"]
}Only the fields that are set are sent. context carries any of LoreMind's context fields; custom context entries are folded into the single context.custom string as key: value pairs separated by |. conversationHistory holds at most the last 50 messages (each at most 10,000 characters), and activeKnowledgeTags at most 50 tags. The request also carries the header Authorization: Bearer <player session token> when you set up the token hook below.
Your backend should:
- Verify the session token and reject the request (
401) if it is missing or invalid - Set
playerIdfrom the verified token (e.g., Steam ID, account ID). Ignore anyplayerIdin the body: anything a game client sends can be forged - Apply a per-player rate limit, and optionally allow only the
entityMindIdvalues your game uses - Add the
Authorization: Bearer YOUR_SERVER_API_KEYheader (the key from an environment variable) - Forward the JSON to LoreMind and return its status, body and
Retry-Afterheader unchanged (see What Your Backend Returns)
Sending the Player's Session Token
CustomBackendTransport can attach your player's session token (from your login system) to every request. Set a token provider once, for example after login:
using Peek.LoreMind.Cloud;
// For every CustomBackendTransport the SDK creates (Control Panel mode)
CustomBackendTransport.DefaultAuthTokenProvider = async () =>
{
return await MyLogin.GetSessionTokenAsync(); // refresh it here if it expires
};The token is sent as Authorization: Bearer <token>. The provider is called before every attempt, so it can refresh an expired token. If it returns nothing or throws, the request is not sent and fails with AUTH_FAILED. For other headers (an API gateway key, a game version), use ConfigureRequest:
var transport = new CustomBackendTransport("https://api.yourgame.com/api/npc/interact")
{
AuthTokenProvider = () => MyLogin.GetSessionTokenAsync(),
ConfigureRequest = request => request.SetRequestHeader("X-Game-Version", Application.version)
};
npc.SetTransport(transport);CustomBackendTransport.DefaultConfigureRequest applies to every instance that has no ConfigureRequest of its own. Redirects are not followed: your Backend URL must answer the request itself.
Dedicated Server Builds
If your NPC conversations run on a Unity Dedicated Server (UNITY_SERVER), the server may call LoreMind directly with DirectApiTransport. Read the key from the server's environment, never from a file in the build:
#if UNITY_SERVER
var key = System.Environment.GetEnvironmentVariable("LOREMIND_SERVER_API_KEY");
npc.SetTransport(new DirectApiTransport("https://loremind.peekgames.dev/api/loremind/v1", key, playerIdFromYourAuth));
#endifOne transport serves one default player. When one server NPC talks to many players, either give each conversation its own DirectApiTransport, or call the transport yourself and set request.playerId on each request (from your own authenticated session): a playerId already on the request is kept. Set the transport mode to SetInCode so the build check does not warn.
What Your Backend Returns
Return LoreMind's response to the game exactly as it came: the same status code, the same JSON body, and the Retry-After header when there is one. The SDK maps the status to the same error codes as in the Editor (RATE_LIMITED, INSUFFICIENT_CREDITS, UNKNOWN_KNOWLEDGE_TAGS, LORE_UNAVAILABLE and so on), so the game can tell an NPC reply from an error.
- Never substitute canned NPC lines. LoreMind never answers an NPC without its lore: if the lore can't be searched, it returns
503 Lore unavailable(and charges nothing) instead of a reply. Your backend shouldn't invent one either. - If LoreMind doesn't answer at all (your timeout fired or the connection dropped), return your own error status, such as
502, not NPC dialogue. - Don't retry in your backend. The SDK already retries a
503that carriesRetry-After: it waits exactly that delay and tries again, up to 3 attempts in all, then reportsLORE_UNAVAILABLEto the game. A backend that retries too multiplies the attempts. If your backend serves a client that doesn't retry and you retry there instead, retry only a503that carriesRetry-After, after that delay. Never retry a timeout.
See Lore Unavailable for the exact response.
A custom backend may also return its own JSON error body ({"success": false, "error": "...", "message": "..."}). If error is one of the SDK error codes, it is kept as is; otherwise the SDK maps the HTTP status and keeps your message.
Timeouts
The first NPC request after a period of inactivity can take much longer than usual, sometimes minutes. LoreMind allows up to 600 seconds per request.
Every timeout between the game and LoreMind must be at least 600 seconds:
- Your backend's HTTP client, calling LoreMind
- Your backend's own request timeout (Cloud Run, Cloud Run functions, AWS Lambda, and so on)
- Any load balancer, API gateway, CDN, or reverse proxy in front of your backend
- The game's request to your backend:
CustomBackendTransportwaits 600 seconds by default (timeoutSeconds). Keep the default or set it longer; don't lower it
Some hosts can't wait that long at all, including PlayFab CloudScript, Amazon API Gateway HTTP APIs, and HTTP-triggered Azure Functions. Server Integration lists the defaults and limits for common platforms. If a hop can't wait that long, that hop sets your worst case: a request it cuts off returns an error to the player, never a reply without lore.
Programmatic Configuration
You can also configure the transport in code. Set Transport Mode to SetInCode in the Control Panel: the settings then create no transport, and the build check doesn't ask for a backend URL.
using Peek.LoreMind.Cloud;
// Set the backend URL programmatically (timeoutSeconds defaults to 600)
var transport = new CustomBackendTransport(
backendUrl: "https://api.yourgame.com/api/npc/interact"
);
npc.SetTransport(transport);This is useful if you need different backends for different environments (dev, staging, production), or your own ILoreMindTransport. Call SetTransport before the NPC's first request: in SetInCode mode an NPC without a transport answers with CONFIG_ERROR.
Long-Term Memory
Memory works only when Long-Term Memory is turned on for your project. LoreMind support turns it on and records the memory agreement; it isn't available for projects marked Players under 18. Your project's page in the LoreMind dashboard shows whether it's on. While it's off, NPCs still answer, but no memories are stored or recalled.
The playerId field is required for all API key requests. Your backend provides it from the verified session token. Memory uses it to identify players across sessions:
// Your backend adds playerId before forwarding to LoreMind
{
"text": "Hello!",
"entityMindId": "em_innkeeper",
"playerId": "steam_76561198012345678",
"memory": { "retrieve": true }
}Good player ID choices:
- Platform IDs:
steam_76561198012345678,epic_abc123 - Game account IDs:
account_12345 - Persistent UUIDs:
550e8400-e29b-41d4-a716-446655440000
Avoid:
- Temporary session IDs (memories won't persist)
- Email addresses (PII concerns)
- Device IDs (players switch devices)
See Long-Term Memory for details.
Testing Checklist
Before shipping, verify:
- API key is stored in backend environment variables (not in code)
- API key is NOT in your game build
- Player authentication works correctly (requests without a valid session token are rejected)
-
playerIdcomes from the verified token, never from the request body - Each player has a request limit
- Every timeout between the game and LoreMind is at least 600 seconds
- Your backend returns LoreMind's status code, JSON body, and
Retry-Afterheader unchanged - Error responses (including
503 Lore unavailable) show the player a "try again" state, never a canned NPC line - Rate limits reviewed in Dashboard
- Long-term memory works (if using)
Security Best Practices
Never Expose Your API Key
- Store it in environment variables on your backend
- Never commit it to version control
- Never include it in game builds
Validate Requests
- Authenticate players before forwarding requests (verify the session token)
- Take
playerIdfrom the verified token; ignore the one in the body - Rate-limit per player; LoreMind's limits protect your project's credits, not against one player flooding your backend
- Consider validating
entityMindIdagainst an allowlist, and reject oversized bodies - If your game runs in a browser (WebGL), allow only your game's origin in CORS
Use HTTPS
- LoreMind API requires HTTPS
- Your backend should require HTTPS too (release builds refuse a non-https Backend URL)
Keep Shipped Builds Patched
- Build with a Unity version that includes the CVE-2025-59489 fix (see Requirements) and rebuild games you already shipped with an older editor
Monitor Usage
- Set up billing alerts in the dashboard
- Review rate limits in Dashboard → Rate Limits
- Track per-player usage if needed
Troubleshooting
"Unauthorized" errors from LoreMind
- Check your API key is correct (starts with
sk_server_) - Verify the key is in the
Authorizationheader - Make sure you're using a Server Key, not an Editor Key
AUTH_FAILED before anything reaches your backend
Your AuthTokenProvider returned no token or threw, so the SDK didn't send the request. Make sure the player is logged in before talking to NPCs.
NPC requests time out after a quiet period
- The first request after a period of inactivity can take much longer than usual
- Make sure every timeout between the game and LoreMind is at least 600 seconds (see Timeouts)
"Lore unavailable" (503) or LORE_UNAVAILABLE
- LoreMind couldn't search the NPC's lore, so it made no reply and charged nothing
- The SDK already waited and retried as the server asked. Let the player try again after
response.retryAfterseconds
UNKNOWN_KNOWLEDGE_TAGS
- None of the NPC's Active Knowledge Tags exist on its Entity Mind, so LoreMind made no reply and charged nothing
- Compare the tags with the Entity Mind's tags in the dashboard (a renamed or removed tag is the usual cause), or clear the list to use all of the mind's tags
"Entity Mind not found"
- Verify the
entityMindIdexists in your dashboard - Check for typos in the ID
Requests not reaching your backend
- Check the Backend URL is correct in the Control Panel (it must be
https; see Step 2) - Verify your backend is running and accessible
- Check for CORS issues if testing in browser
Memory not working
- Check that Long-Term Memory is on for your project: your project's page in the LoreMind dashboard shows its status. LoreMind support turns it on; it isn't available for projects marked Players under 18
- Ensure your backend adds
playerId(from the verified player token) to requests - Use consistent player IDs across sessions
- Verify
memory: { retrieve: true }is included (EnableMemoryRetrievalon the NPC)
Next Steps
- Server Integration - Backend code examples for all platforms
- Long-Term Memory - Make NPCs remember players
- API Reference: full API documentation