# ERP (JTL-Wawi) Source: https://developer.jtl-software.com/cloud/api-reference/erp REST and GraphQL access to JTL-Wawi business data The ERP API lets you read and manipulate data in JTL-Wawi: orders, products, customers, invoices, inventory, and more. It is available as a REST API (all versions) and, starting with v2.0, as a GraphQL API. > [card] [Integration Overview](/cloud/guides/erp-integration/integration-overview) > > Auth, headers, deployment variants, and how to make your first call. > [card] [GraphQL API](/cloud/api-reference/graphql) > > Available from v2.0. Browse every query, mutation, and type by business area. ## OpenAPI Spec Download the spec for any supported version. Import into Postman, Insomnia, or generate a client. Each API version ships with a specific JTL-Wawi release, and a single JTL-Wawi release usually ships more than one API version. The table groups the available API versions by the JTL-Wawi version they ship with. The version selector shows the same JTL-Wawi version next to each API version. | JTL-Wawi Version | API Version | Status | Spec | | - | - | - | - | | 2.3.x | v3.0 | Pre-release | [Download JSON](/openapi/erp/3.0.json) | | 2.3.x | v2.2 | Pre-release | [Download JSON](/openapi/erp/2.2.json) | | 2.3.x | v1.5 | Pre-release | [Download JSON](/openapi/erp/1.5.json) | | 2.2.x | v2.1 | Latest, recommended | [Download JSON](/openapi/erp/2.1.json) | | 2.2.x | v1.4 | Supported | [Download JSON](/openapi/erp/1.4.json) | | 2.1.x | v2.0 | Supported | [Download JSON](/openapi/erp/2.0.json) | | 2.1.x | v1.3 | Supported | [Download JSON](/openapi/erp/1.3.json) | | 2.0.x | v1.2 | Supported | [Download JSON](/openapi/erp/1.2.json) | | 1.11.x | v1.1 | Supported | [Download JSON](/openapi/erp/1.1.json) | | Not specified | v1.0 | Supported | [Download JSON](/openapi/erp/1.0.json) | # GraphQL API Source: https://developer.jtl-software.com/cloud/api-reference/graphql Reference for the JTL ERP GraphQL API: every query, mutation, and type, grouped by business area. The JTL ERP GraphQL API provides a single endpoint for querying and modifying JTL-Wawi data. It is available starting with API version v2.0. This reference documents every query, mutation, and type in the schema, organised by business area such as **Items**, **Sales**, and **Inventory**. Each area contains its operations and the types they use. Types shared across multiple areas are documented under **Common Types**. Use the version selector to switch the reference to the API version your app targets. ## Endpoint and Authentication Send all requests as HTTP `POST` requests to: ``` https://api.jtl-cloud.com/erp/v2/graphql ``` Every request needs: * An `Authorization: Bearer ` header. See [OAuth 2.0 Flow](/cloud/guides/essentials/authentication/oauth2-flow). * An `x-tenant-id` header with the tenant ID of the target JTL-Wawi instance. For request examples in several languages, see [Using Platform APIs](/cloud/guides/cloud-apps/using-platform-apis#graphql-api). ## Reading a Reference Page Each query and mutation reference includes: * The operation's arguments and return type, with links to the types they reference. * An example operation, its required variables, and a sample response. * Deprecated fields and arguments, including the reason for deprecation when available in the schema. The schema follows consistent patterns for naming, pagination, and filtering. See [GraphQL Conventions](/cloud/guides/essentials/common-patterns/graphql-conventions) for an overview of these patterns and how to use them when querying the API. ### Scopes Each operation page lists the scopes your app needs to call it. To learn how to request scopes for your app, see [Scopes and Permissions](/cloud/guides/essentials/authentication/scopes-permissions). ### Release Status Some operations and fields have a release status such as **Beta** or **Experimental**. These are not yet stable and may change between releases. Check the status before using them in production. Operations and fields without a release status are considered stable. ## Try a Query Use the [GraphQL Playground](/cloud/api-reference/graphql-playground) to write and run queries and mutations against the API. Sign in to execute operations against your own JTL-Wawi instance. ## Download the Schema Download the complete schema in GraphQL Schema Definition Language (SDL) format for a specific API version. You can use it to generate typed clients, validate queries, or integrate the schema into your development tools. | API version | JTL-Wawi version | Status | Schema | | - | - | - | - | | v3.0 | 2.3.x | Pre-release | [Download SDL](/graphql/erp/3.0.graphql.txt) | | v2.2 | 2.3.x | Pre-release | [Download SDL](/graphql/erp/2.2.graphql.txt) | | v2.1 | 2.2.x | Latest, recommended | [Download SDL](/graphql/erp/2.1.graphql.txt) | | v2.0 | 2.1.x | Supported | [Download SDL](/graphql/erp/2.0.graphql.txt) | The files use a `.txt` extension so the docs site can serve them. Rename a downloaded file to `.graphql` before you use it with codegen tools. # GraphQL Playground Source: https://developer.jtl-software.com/cloud/api-reference/graphql-playground Interactive GraphQL IDE to explore and test the JTL Platform API Explore the JTL ERP API using GraphQL. Use the schema explorer on the left to browse available queries and mutations, or type directly in the editor. Log in to run queries against your own ERP instance. [GraphQL Playground](https://jtl-software.github.io/devdocs-graphql-playground/?url=https://api.jtl-cloud.com/erp/v2/graphql) ## Best Viewed on Desktop The GraphQL playground is a full interactive IDE built for larger screens. Open this page on a desktop or tablet to browse the schema and run queries. # Create a Developer Account Source: https://developer.jtl-software.com/cloud/get-started/create-developer-account Set up your development environment in three connected steps. Takes about 10 minutes. To build on the JTL platform, you'll work across four connected environments. Each one plays a different role in your development workflow. Three of them are needed to start building, and the fourth comes in when you're ready to test your app. This guide walks you through setting them up in one go. It takes about 10 minutes. ## Your Development Environment Here's what each environment does and why you need it: | Environment | What you'll use it for | | - | - | | **[JTL-Wawi](/cloud/guides/erp-integration/integration-overview)** | The ERP system where merchant data lives: products, orders, customers, inventory. Your app reads and writes this data through APIs or GraphQL. | | **[Partner Portal](https://partner.jtl-cloud.com/)** | Where you create and manage your apps. | | **[JTL Hub](https://hub.jtl-cloud.com/)** | A dedicated environment where you can install and test your apps, verify the connection to JTL-Wawi, and manage the app lifecycle before going live. | | **[Cloud ERP](https://erp.jtl-cloud.com/)** | The web-based interface where your installed app actually runs. Currently in development, with MVP release coming soon. You can already use it to test your app and validate how it integrates. See [Test your App](/cloud/get-started/test-your-app). | > [!NOTE] > > **JTL-Wawi** is the ERP itself (the data), **Partner Portal** is where you > create and manage your apps, **JTL Hub** is where you install, and **ERP > Cloud** is where your app runs for the merchant. Here's how they connect: ```mermaid theme={null} flowchart LR subgraph You["👤 Developer"] direction TB end subgraph Create["1 · Partner Portal"] direction TB PP["**Create & configure apps** Manage credentials Handle submissions & payouts"] end subgraph Install["2 · JTL Hub"] direction TB HC["**Sandbox environment** Install & test apps Manage app lifecycle"] end subgraph Run["3 · Cloud ERP"] direction TB EP["**App runtime** Where your installed app actually renders"] end subgraph Data["JTL-Wawi"] direction TB WW["**ERP system** Products, orders, customers, inventory & shipping"] end subgraph Ship["🚀 App Store"] direction TB ES["Distribute to 50,000+ merchants"] end You --> Create Create -- "App credentials" --> Install Install -- "Launches app" --> Run Run -- "APIs" --> Data Install -- "Submit" --> Ship style Create fill:#FFF2EB,stroke:#FB581F,stroke-width:2px,color:#0B1B45 style Install fill:#E8F4FF,stroke:#89D2FF,stroke-width:2px,color:#0B1B45 style Run fill:#E8F4FF,stroke:#89D2FF,stroke-width:2px,color:#0B1B45 style Data fill:#FFF2EB,stroke:#FB581F,stroke-width:2px,color:#0B1B45 style Ship fill:#FFF2EB,stroke:#FB581F,stroke-width:2px,color:#0B1B45 style You fill:#EEEEE7,stroke:#0B1B45,stroke-width:2px,color:#0B1B45 ``` The overall flow is: you **create your app** in the Partner Portal, **install it** in JTL Hub, **run it** in the Cloud ERP against **live data from JTL-Wawi**, and when everything looks good, **submit it** to the App Store. Now let's get everything set up. ## Step 1: Set up your Partner Portal This is your app management hub where you create apps and get your client credentials. **1. Go to the Partner Portal** Open [Partner Portal](https://partner.jtl-cloud.com/) in your browser. **2. Create your JTL ID** > [!WARNING] > > SSO is currently not supported with your JTL ID. You'll need to register separately with your email. Once you navigate to the URL, you'll be prompted to log in with your **JTL ID**. Click on the **Register now** button to create a new JTL ID. **JTL ID** provides a single access point to all JTL cloud-related services (JTL Hub, Partner Portal, Cloud ERP, etc.) ![Partner Portal registration screenshot](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/Partner_JTL_register.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=32f1a4d27c3d5ac5cf05d5af5e598e14) On registering, you'll be asked to fill in the confirmation code sent to your email address. Once you fill in the code, you'll be automatically logged in. > [!NOTE] > > If you created your account with the **Password** option, it’s recommended to set up 2FA before proceeding. **3. Create a Customer Center Account** Choose one of the following: ![Create or link customer account](https://mintcdn.com/jtlsoftwaregmbh/cErpio_7WC4XxfEi/images/create_or_link.png?fit=max\&auto=format\&n=cErpio_7WC4XxfEi\&q=85\&s=eea357674f7b5a043a3bb76fb2ce466d) * **New to JTL**: Click **Create organization** and fill in the required details if you don't have an existing Customer Center Account. * **Existing JTL customer**: Click **Link your JTL customer account** and log in to your Customer Center Account. Then **Authorize** JTL Cloud when prompted. > [!TIP] > > **Customer Center Account** is your central hub for managing licenses, JTL > services, billing, and support. After completing either option above, continue with the steps below: 1. Once your organization is created, you’ll be redirected to [Partner Portal](https://partner.jtl-cloud.com/) onboarding page with your organization name and custom URL path. Next, select how you want to use the Partner Portal and then **Continue**. ![How to use Partner Portal](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/Partner_JTL_how_to_use.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=4ee06eb1a1e82f86c58f2741ac173dab) 2. Enter your business contact details and **Create account**. ![Business contact details](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/business_contact_details.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=d11ea5db78bbea4087327dc7c63a762c) Once your account is created, you’ll be redirected to the Partner Portal dashboard. This is where you'll create and manage your apps. ![Partner Portal dashboard](https://mintcdn.com/jtlsoftwaregmbh/cErpio_7WC4XxfEi/images/partner_portal_dashboard.png?fit=max\&auto=format\&n=cErpio_7WC4XxfEi\&q=85\&s=756096dd071ab527263a0f59f38bd006) ## Step 2: Connect to JTL-Wawi The final step is to connect your JTL Cloud environment to JTL-Wawi. Your app uses this connection to read and write merchant data. **1. Initiate connection from JTL-Wawi** Log in to your JTL-Wawi instance. In the **Admin** menu, click **JTL Cloud connection (JTL Cloud verbindung)**, then click **Connect**. ![JTL Cloud > Connect option](https://mintcdn.com/jtlsoftwaregmbh/_2ZZJDr-y_bgfn7P/images/JTL_cloud_connect.png?fit=max\&auto=format\&n=_2ZZJDr-y_bgfn7P\&q=85\&s=51778be86b276762d47119f8f83501eb) Read the message in the dialog carefully and click **OK**. This opens a new tab with the JTL Cloud login page. **2. Log in to JTL Cloud** Log in using the JTL ID you created in [Step 1](#step-1-set-up-your-partner-portal). Once authentication is successful, close the browser tab and return to your JTL-Wawi instance. **3. Confirm connection status** Back in JTL-Wawi, you'll see a **Connected** status, indicating the pairing was successful. ![Connected Wawi instance](https://mintcdn.com/jtlsoftwaregmbh/_2ZZJDr-y_bgfn7P/images/JTL_connection_statuses.png?fit=max\&auto=format\&n=_2ZZJDr-y_bgfn7P\&q=85\&s=9599320f8ddd2b13a693ef218072489a) **4. Start the Wawi API** Pairing JTL-Wawi with JTL Cloud is not sufficient on its own. You must also configure and start the Wawi API so your app can access and sync data. Open the **JTL Administrator** to start the Wawi API. > [!NOTE] > > JTL creates a desktop shortcut for the JTL Administrator after installation.\ > For older versions of JTL-Wawi, you can find it in the installation folder. Create a new entry by selecting **Wawi-API**. ![Create new API entry](https://mintcdn.com/jtlsoftwaregmbh/_2ZZJDr-y_bgfn7P/images/admin_wawi_api.png?fit=max\&auto=format\&n=_2ZZJDr-y_bgfn7P\&q=85\&s=ecb9ad4dcc5e098c50ba61049395f475) Select the desired profile and certificate, then enable the **Cloud Connection** checkbox. Click **Save**. ![Cloud Connection via JTL Administrator](https://mintcdn.com/jtlsoftwaregmbh/_2ZZJDr-y_bgfn7P/images/wawi_api_form.png?fit=max\&auto=format\&n=_2ZZJDr-y_bgfn7P\&q=85\&s=dff3c6ccc596d46c7e3dc78fe52f85df) Once the connection is established, you will see an **is running** status. This may take a few seconds. ![Connected Wawi instance](https://mintcdn.com/jtlsoftwaregmbh/_2ZZJDr-y_bgfn7P/images/connected_wawi_to_cloud.png?fit=max\&auto=format\&n=_2ZZJDr-y_bgfn7P\&q=85\&s=e7a7767f87390ec6d8b75cfed0ce3f47) You can start or stop the API service from the JTL Administrator. > [!WARNING] > > If the API service is stopped, Cloud Apps cannot read or write data. **5. Verify in JTL Hub** Navigate to the **Connection status** menu in [JTL Hub](https://hub.jtl-cloud.com/) to see your connected Wawi instance. ![Connected Wawi instance](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/connected_wawi.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=e3e4f4c5604ba8b0fa691f9809449290) You now have everything you need to start building Cloud Apps. ## What's Next? > [card] [Quickstart: From Template](/cloud/get-started/quick-start/from-template) > > Start from a template and get a Cloud App running in minutes. Recommended for most developers. > [card] [Quickstart: From Scratch](/cloud/get-started/quick-start/from-scratch) > > Build a Cloud App step by step to understand how everything fits together. > [!NOTE] > > **Need help?** If you run into issues during account setup, reach out via the [support channel](/help/support). # C# Source: https://developer.jtl-software.com/cloud/get-started/quick-start/from-scratch/backend-csharp Build the ASP.NET Core backend for your JTL Cloud App. Verify app tokens, fetch access tokens, and proxy requests to the JTL Cloud API. Build the ASP.NET Core backend for a JTL Cloud App using .NET 8 and `Microsoft.IdentityModel.Tokens` for JWT verification. By the end, the backend runs locally and the frontend's "Connecting to JTL Platform…" placeholder turns into a real connection. **Stack:** .NET 8, ASP.NET Core Web API, `Microsoft.IdentityModel.Tokens` for app token verification. ## Prerequisites You need: * ✅ **A finished frontend** from the [Build the Frontend](/cloud/get-started/quick-start/from-scratch/frontend) page, running locally on `http://localhost:5173` * ✅ **[.NET SDK](https://dotnet.microsoft.com/download) 8.0 or higher**. Run `dotnet --version` to check. ## What you're Building During setup, your backend verifies that the app token from your frontend is valid and was issued by JTL for your app. To do this: * Your backend fetches the identity provider's public keys (JWKS) * Verifies the token's signature, issuer, and expiry against them * Confirms the token's audience is your app, so a token minted for another app is rejected ```mermaid theme={null} sequenceDiagram participant FE as Your Frontend participant BE as Your Backend (ASP.NET Core) participant IDP as JTL Identity Provider FE->>BE: GET /api/connect-tenant (Bearer app token) BE->>IDP: GET /oauth/v2/keys IDP-->>BE: Public keys (JWKS) BE->>BE: Verify signature, issuer, expiry, audience BE-->>FE: Verified tenant info ``` Once verified, the token tells your backend which tenant (merchant) and user is using your app. Your backend can then make tenant-scoped requests to the JTL Cloud API on their behalf, authenticating with its own client credentials. ## 1. Set up the Project Create a `Backend` folder alongside the existing `frontend` folder, then scaffold a Web API project inside it. ```bash theme={null} cd my-jtl-app dotnet new webapi -n Backend ``` Your project structure now looks like this: ``` my-jtl-app/ ├── frontend/ # From the previous page └── Backend/ # New ``` The `dotnet new webapi` template includes a sample `WeatherForecast` controller and model. You can leave these in place or delete them. They won't affect anything you build in this guide. ## 2. Install Packages ```bash theme={null} cd Backend dotnet add package Microsoft.IdentityModel.Tokens dotnet add package System.IdentityModel.Tokens.Jwt ``` | Package | Purpose | | - | - | | `Microsoft.IdentityModel.Tokens` | JWKS parsing and token validation parameters | | `System.IdentityModel.Tokens.Jwt` | JWT handler for reading and validating app tokens | ## 3. Set up Environment Variables ASP.NET Core uses `appsettings.json` for configuration. For local secrets, use the .NET user-secrets tool so credentials never end up in source control. From the `Backend/` directory: ```bash theme={null} dotnet user-secrets init dotnet user-secrets set "Jtl:ClientId" "your-client-id-here" dotnet user-secrets set "Jtl:ClientSecret" "your-client-secret-here" dotnet user-secrets set "Jtl:AppId" "your-app-id-here" dotnet user-secrets set "Jtl:Issuer" "https://id.jtl-cloud.com" ``` The values are placeholders for now. You'll get real values from the [Partner Portal](https://partner.jtl-cloud.com/) in the next page and update them with the same `dotnet user-secrets set` commands. `Jtl:AppId` is your app's ID, which an app token's audience must contain. `Jtl:Issuer` is the identity provider that issues app tokens. For production, swap user-secrets for environment variables, Azure Key Vault, or whichever secrets manager fits your hosting platform. ## 4. Build the Auth Service The first piece of the backend is a service that authenticates with JTL using your client credentials and returns an access token. Your backend uses it to make tenant-scoped calls to the JTL Cloud API. Create `Backend/Services/JtlAuthService.cs`: ```csharp theme={null} using System.Net.Http.Headers; using System.Text; using System.Text.Json; namespace Backend.Services; public class JtlAuthService { private readonly HttpClient _http; private readonly IConfiguration _config; public JtlAuthService(HttpClient http, IConfiguration config) { _http = http; _config = config; } public string ApiBaseUrl => "https://api.jtl-cloud.com"; private string AuthEndpoint { get { var issuer = (_config["Jtl:Issuer"] ?? "https://id.jtl-cloud.com").TrimEnd('/'); return $"{issuer}/oauth/v2/token"; } } public async Task GetJwtAsync() { var clientId = _config["Jtl:ClientId"]; var clientSecret = _config["Jtl:ClientSecret"]; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) { throw new InvalidOperationException( "Jtl:ClientId and Jtl:ClientSecret must be configured."); } var basic = Convert.ToBase64String( Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); var request = new HttpRequestMessage(HttpMethod.Post, AuthEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", basic); request.Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["scope"] = "openid", }); var response = await _http.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new HttpRequestException( $"Failed to fetch JWT ({(int)response.StatusCode}): {body}"); } using var doc = JsonDocument.Parse(body); return doc.RootElement.GetProperty("access_token").GetString()!; } } ``` The service reads its credentials from `IConfiguration` (which user-secrets feeds into automatically), encodes them as Basic auth, and sends a `client_credentials` grant request to JTL's auth endpoint. The method fetches a fresh token on each call. For higher-traffic backends you'd add caching. See [Service Account Authentication](/cloud/guides/cloud-apps/service-account-authentication#caching-the-token). ## 5. Build the Token Verifier The backend verifies the app token before trusting anything in it. `Microsoft.IdentityModel.Tokens` parses the identity provider's key set, selects the key matching the token's `kid`, and validates the signature, issuer, expiry, and audience in one pass. Create `Backend/Services/AppTokenVerifier.cs`: ```csharp theme={null} using System.IdentityModel.Tokens.Jwt; using Microsoft.IdentityModel.Tokens; namespace Backend.Services; public class AppTokenVerifier { private readonly HttpClient _http; private readonly IConfiguration _config; private JsonWebKeySet? _keys; public AppTokenVerifier(HttpClient http, IConfiguration config) { _http = http; _config = config; } private string Issuer => (_config["Jtl:Issuer"] ?? "https://id.jtl-cloud.com").TrimEnd('/'); private string AppId => (_config["Jtl:AppId"] ?? "").Trim(); public async Task VerifyAsync(string token) { _keys ??= new JsonWebKeySet( await _http.GetStringAsync($"{Issuer}/oauth/v2/keys")); var parameters = new TokenValidationParameters { ValidIssuer = Issuer, ValidateIssuer = true, ValidAudience = AppId, ValidateAudience = true, IssuerSigningKeys = _keys.Keys, ValidateIssuerSigningKey = true, ValidateLifetime = true, RequireExpirationTime = true, }; new JwtSecurityTokenHandler().ValidateToken(token, parameters, out var validated); var jwt = (JwtSecurityToken)validated; var appIdClaim = jwt.Claims .FirstOrDefault(c => c.Type == "urn:jtl:app_id")?.Value; if (appIdClaim is not null && appIdClaim != AppId) { throw new SecurityTokenInvalidAudienceException( "Token was minted for a different app."); } return jwt; } } ``` `ValidateToken` performs four checks at once: the signature against the key whose `kid` matches the token header, the issuer, the expiry, and that the audience contains your app ID. Any failure throws. The `urn:jtl:app_id` claim is optional and is not covered by `ValidateAudience`, so it needs its own check. When the claim is absent the token is valid for your app, and when it is present it must equal your app ID. The key set is fetched on first use and held for the lifetime of the service. Public keys change infrequently, so refetching on every request adds latency for no benefit. ## 6. Build the Connect Tenant Controller Now wire the verifier into a controller. The frontend's shell layout sends the app token to the backend as a Bearer token and expects a claim with the tenant information including tenant ID, client ID, etc. Create `Backend/Controllers/ConnectTenantController.cs`: ```csharp theme={null} using Backend.Services; using Microsoft.AspNetCore.Mvc; namespace Backend.Controllers; [ApiController] [Route("api/connect-tenant")] public class ConnectTenantController : ControllerBase { private readonly AppTokenVerifier _verifier; public ConnectTenantController(AppTokenVerifier verifier) { _verifier = verifier; } [HttpGet] public async Task Get() { var authHeader = Request.Headers.Authorization.ToString(); var token = authHeader.StartsWith("Bearer ") ? authHeader[7..] : ""; if (string.IsNullOrWhiteSpace(token)) { return BadRequest(new { error = "App token is required" }); } try { var jwt = await _verifier.VerifyAsync(token); var tenantId = jwt.Claims .FirstOrDefault(c => c.Type == "urn:jtl:tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) { return BadRequest(new { error = "App token has no tenant claim" }); } // In a production app, you'd store the tenant connection in your database here return Ok(new { success = true, tenantId, clientId = jwt.Claims.FirstOrDefault(c => c.Type == "client_id")?.Value, }); } catch (Exception) { return Unauthorized(new { error = "Failed to verify app token" }); } } } ``` The controller reads the app token from the `Authorization` header, hands it to the verifier, and returns the tenant details on success or a 401 on failure. The `[ApiController]` attribute handles model binding and validation automatically. See [Tenant Mapping](/cloud/guides/cloud-apps/app-token-authentication#tenant-mapping) for more on managing tenants in production. ## 7. Wire up Services and CORS ASP.NET Core needs to know about the services it should inject and the controllers it should expose. Replace the contents of `Backend/Program.cs`: ```csharp theme={null} using Backend.Services; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddHttpClient(); builder.Services.AddHttpClient(); // Allow the Vite dev server to call the API during development builder.Services.AddCors(options => { options.AddDefaultPolicy(policy => { policy.WithOrigins("http://localhost:5173") .AllowAnyHeader() .AllowAnyMethod(); }); }); var app = builder.Build(); app.UseCors(); app.MapControllers(); app.Run(); ``` `AddHttpClient` does two things at once: it registers the service in the DI container and gives each instance its own `HttpClient` from the built-in factory. `AppTokenVerifier` is registered as transient, so its key set cache lives for one request. For production, register it as a singleton so the keys are fetched once per process. The CORS policy allows requests from the Vite dev server on port 5173. The dev proxy in `vite.config.ts` already routes frontend `fetch('/api/...')` calls to this backend, but the CORS middleware is a useful safety net during development. ## 8. Configure the Backend Port By default, `dotnet new webapi` listens on a random port chosen at startup, but the frontend's Vite dev proxy expects the backend on `http://localhost:5273`. Pin the port in `Backend/Properties/launchSettings.json` by replacing the `applicationUrl` value in the `http` profile: ```json theme={null} { "profiles": { "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, "applicationUrl": "http://localhost:5273", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ``` You can leave the other profiles (`https`, `IIS Express`) in place. The `dotnet run` command picks the `http` profile by default during development. ## 9. Run the Backend Start the backend: ```bash theme={null} dotnet run ``` You should see output like: ``` Now listening on: http://localhost:5273 Application started. Press Ctrl+C to shut down. ``` In a second terminal, send a request with a fake app token to confirm the route is reachable: ```bash theme={null} curl http://localhost:5273/api/connect-tenant \ -H "Authorization: Bearer fake-token" ``` You should get back a `401` response with `{"error":"Failed to verify app token"}`. A real app token from the App Shell will follow the same path and succeed. ## Common Issues > [accordion] 'Jtl:ClientId and Jtl:ClientSecret must be configured' > > This error means the backend started but couldn't find your credentials in configuration. The most common cause is that user-secrets weren't initialised, or were set in a different directory than the project expects. > > User-secrets are scoped to a specific project, identified by the `UserSecretsId` GUID in the `.csproj` file. Running `dotnet user-secrets list` from inside the `Backend/` directory will show whether the secrets are present for this project. If the list comes back empty, running `dotnet user-secrets init` followed by the two `dotnet user-secrets set` commands from earlier in the guide will populate them. > > It's also worth confirming that you ran the user-secrets commands from the `Backend/` directory and not the project root. The tool resolves the target project based on the current working directory. > [accordion] 'Failed to fetch JWT (401)' from the auth endpoint > > A 401 from JTL's auth endpoint means the credentials being sent aren't recognised. Until you've registered your app in the Partner Portal, this is the expected response, since the placeholder values from earlier aren't real credentials. The next page in this guide walks through registration and provides the real values. > > If you've already registered the app and are still seeing this error, the most likely causes are typos in the user-secrets values and forgetting to restart the backend after updating them. ASP.NET Core reads configuration once at startup, so changes to user-secrets take effect only on the next `dotnet run`. The `dotnet user-secrets list` command is the fastest way to confirm the stored values match what the Partner Portal showed you. > [accordion] 'Failed to verify app token' with real credentials > > Verification checks the signature, issuer, expiry, and audience. The audience check is the one most often wrong: `Jtl:AppId` is the app ID shown in the Partner Portal under your app, not the client ID. > > If the audience is correct, confirm `Jtl:Issuer` matches the environment your app is registered in. A token issued by one environment does not verify against another's keys. > > App tokens are valid for about an hour, so a token captured earlier during debugging will fail on expiry. > [accordion] CORS error in the browser console > > A CORS error usually means the request reached the backend but the browser blocked the response because the origin didn't match what the backend allows. The CORS policy in `Program.cs` is configured to allow `http://localhost:5173`, which matches the default Vite dev server port. > > If the Vite dev server is running on a different port (for example, because port 5173 was already in use and Vite picked 5174 instead), the browser will see a mismatch. Updating the `WithOrigins` value in `Program.cs` to match the actual Vite port, or freeing up port 5173, should resolve it. > > Worth noting: when the Vite dev proxy is forwarding `/api/*` requests, the browser shouldn't actually see CORS at all, since the requests look same-origin from the browser's perspective. CORS errors usually appear when something is calling the backend directly on `localhost:5273` instead of going through the proxy. > [accordion] Backend starts on a different port than 5273 > > If `dotnet run` reports a different port (for example, 5000 or a random high number), the `launchSettings.json` change from earlier in the guide either hasn't been saved or isn't being picked up. > > Confirming that `Backend/Properties/launchSettings.json` contains `"applicationUrl": "http://localhost:5273"` in the `http` profile, then stopping and restarting `dotnet run`, should pin the port. If `dotnet run` is using a different profile than expected, passing `--launch-profile http` explicitly will force it to use the right one. > > An alternative if you'd rather not edit `launchSettings.json` is to set the `ASPNETCORE_URLS` environment variable: `ASPNETCORE_URLS=http://localhost:5273 dotnet run`. This works without any config file changes. ## Next: Connect and Fetch Data The backend verifies app tokens and is ready to call the JTL Cloud API.. The remaining work is registering your app with JTL to get real credentials, installing the app in the JTL Hub, and pulling product data from JTL-Wawi: > [card] [Connect and Fetch Data](/cloud/get-started/quick-start/from-scratch/connect-and-fetch) > > Register your app, install it in the JTL Hub, and fetch products from JTL-Wawi. # Node.js Source: https://developer.jtl-software.com/cloud/get-started/quick-start/from-scratch/backend-node Build the Express backend for your JTL Cloud App. Verify app tokens, fetch access tokens, and proxy requests to the JTL Cloud API. Build the Express backend for a JTL Cloud App using Node.js, TypeScript, and the JTL auth library for app token verification. By the end, the backend runs locally and the frontend's "Connecting to JTL Platform…" placeholder turns into a real connection. **Stack:** Node.js 24.16.0+, Express, TypeScript, `@jtl-software/cloud-apps-auth` for app token verification. ## Prerequisites You need: * ✅ **A finished frontend** from the [Build the Frontend](/cloud/get-started/quick-start/from-scratch/frontend) page, running locally on `http://localhost:5173` * ✅ **[Node.js](https://nodejs.org/) v24.16.0 or higher** (current LTS, includes `npm`). Verify with `node --version` and `npm --version` ## What you're Building During setup, your backend verifies that the app token from your frontend is valid and was issued by JTL for your app. To do this: * Your backend fetches the identity provider's public keys (JWKS) * Verifies the token's signature, issuer, and expiry against them * Confirms the token's audience is your app, so a token minted for another app is rejected ```mermaid theme={null} sequenceDiagram participant FE as Your Frontend participant BE as Your Backend (Express) participant IDP as JTL Identity Provider FE->>BE: GET /api/connect-tenant (Bearer app token) BE->>IDP: GET /oauth/v2/keys IDP-->>BE: Public keys (JWKS) BE->>BE: Verify signature, issuer, expiry, audience BE-->>FE: Verified tenant info ``` Once verified, the token tells your backend which tenant (merchant) and user is using your app. Your backend can then make tenant-scoped requests to the JTL Cloud API on their behalf, authenticating with its own client credentials. ## 1. Set up the Project Create a `backend` folder alongside the existing `frontend` folder, then initialize it. ```bash theme={null} cd my-jtl-app mkdir backend cd backend npm init -y ``` Your project structure now looks like this: ``` my-jtl-app/ ├── frontend/ # From the previous page └── backend/ # New ``` ## 2. Install Packages ```bash theme={null} npm install express cors jose @jtl-software/cloud-apps-auth npm install -D typescript tsx @types/node @types/express @types/cors ``` | Package | Purpose | | - | - | | `express` | HTTP server and routing | | `cors` | Allows the frontend dev server to call the backend during development | | `jose` | JSON Web Token (JWT) operations, used by `@jtl-software/cloud-apps-auth` | | `@jtl-software/cloud-apps-auth` | Verifies app tokens against the identity provider's public keys | | | `typescript` | Type checking and `tsc` compiler | | `tsx` | Runs TypeScript files directly during development without a build step | | `@types/*` | Type definitions for the runtime packages | ## 3. Configure TypeScript Create `backend/tsconfig.json`: ```json theme={null} { "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "outDir": "dist", "rootDir": "src" }, "include": ["src/**/*"] } ``` This configuration uses Node's native ESM support (`NodeNext`) with strict type checking. The `outDir` and `rootDir` settings keep compiled output separate from source files when you eventually build for production. ## 4. Set up Environment Variables The backend needs four values. `CLIENT_ID` and `CLIENT_SECRET` are the credentials JTL issues when you create your app. `JTL_APP_ID` is your app's ID, which an app token's audience must contain. `JTL_ISSUER` is the identity provider that issues app tokens. You will get the real values from the [Partner Portal](https://partner.jtl-cloud.com) in the next page. For now, create the file with placeholder values so the rest of the setup works. Create `backend/.env`: ```dotenv theme={null} CLIENT_ID=your-client-id-here CLIENT_SECRET=your-client-secret-here JTL_APP_ID=your-app-id-here JTL_ISSUER=https://id.jtl-cloud.com PORT=5273 ``` The frontend's Vite dev proxy is already configured to forward `/api/*` requests to `localhost:5273`, so the `PORT` value matches that target. Add `.env` to `backend/.gitignore` so the secrets don't end up in version control: ``` node_modules dist .env ``` ## 5. Build the Auth Helper The first piece of the backend is a function that authenticates with JTL using your client credentials and returns an access token. Your backend uses it to make tenant-scoped calls to the JTL Cloud API. Create `backend/src/jtl-auth.ts`: ```typescript theme={null} const JTL_ISSUER = (process.env.JTL_ISSUER ?? 'https://id.jtl-cloud.com').replace( /\/$/, '', ); const AUTH_ENDPOINT = `${JTL_ISSUER}/oauth/v2/token`; const TOKEN_SCOPE = 'openid'; const API_BASE_URL = 'https://api.jtl-cloud.com'; export function getApiBaseUrl(): string { return API_BASE_URL; } export async function getJwt(): Promise { const clientId = process.env.CLIENT_ID; const clientSecret = process.env.CLIENT_SECRET; if (!clientId || !clientSecret) { throw new Error('CLIENT_ID and CLIENT_SECRET must be defined in .env'); } const authString = Buffer.from(`${clientId}:${clientSecret}`).toString( 'base64', ); const body = new URLSearchParams({ grant_type: 'client_credentials' }); body.set('scope', TOKEN_SCOPE); const response = await fetch(AUTH_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Basic ${authString}`, }, body, }); const data = await response.json(); if (!response.ok) { throw new Error( `Failed to fetch JWT (${response.status}): ${data.error}`, ); } return data.access_token; } ``` This encodes the client credentials as Base64, sends a `client_credentials` grant request to JTL's auth endpoint, and returns the resulting access token. The function fetches a fresh one on each call. For higher-traffic backends you'd add caching. See [Service Account Authentication](/cloud/guides/cloud-apps/service-account-authentication#caching-the-token). ## 6. Build the Token Verifier The backend verifies the app token before trusting anything in it. `verifyAppToken` fetches the identity provider's public keys, checks the signature, issuer, and expiry, then confirms the token was minted for your app. Create `backend/src/verify-app-token.ts`: ```typescript theme={null} import { verifyAppToken } from '@jtl-software/cloud-apps-auth/verify'; import type { JWTPayload } from 'jose'; const ISSUER = (process.env.JTL_ISSUER ?? 'https://id.jtl-cloud.com').replace( /\/$/, '', ); const APP_ID = (process.env.JTL_APP_ID ?? '').trim(); export async function verify(token: string): Promise { const result = await verifyAppToken(token, { issuer: ISSUER, appId: APP_ID, }); if (!result.valid) { throw new Error( `App token verification failed: ${JSON.stringify(result.checks)}`, ); } return result.claims!; } ``` `verifyAppToken` runs three checks and returns a breakdown rather than throwing, so you can report which one failed: | Check | Passes when | | - | - | | `signatureAndIssuer` | The signature validates against the identity provider's keys, `iss` matches, and `exp` is present and in the future | | `audience` | `aud` contains your app ID | | `appId` | `urn:jtl:app_id` is absent, or equals your app ID | `result.valid` is true only when all three pass. The key set is fetched on first use and cached, so repeated verifications do not hit the network. ## 7. Build the Connect Tenant Endpoint Now connect the verifier into an Express route. The frontend's shell layout sends the app token to the backend as a Bearer token and expects a claim with the tenant information including tenant ID, client ID, etc. Create `backend/src/server.ts`: ```typescript theme={null} import express, { type Request, type Response } from 'express'; import cors from 'cors'; import { verify } from './verify-app-token.js'; const app = express(); const port = Number(process.env.PORT) || 5273; app.use(cors({ origin: 'http://localhost:5173' })); app.use(express.json()); app.get('/api/connect-tenant', async (req: Request, res: Response) => { const authHeader = req.headers.authorization ?? ''; const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : ''; if (!token) { return res.status(400).json({ error: 'App token is required' }); } try { const claims = await verify(token); const tenantId = claims['urn:jtl:tenant_id']; if (typeof tenantId !== 'string') { return res.status(400).json({ error: 'App token has no tenant claim' }); } // In a production app, you'd store the tenant connection in your database here return res.json({ success: true, tenantId, clientId: claims.client_id, }); } catch { return res.status(401).json({ error: 'Failed to verify app token' }); } }); app.listen(port, () => { console.log(`Backend listening on http://localhost:${port}`); }); ``` CORS is configured to allow requests from the Vite dev server on port 5173. The dev proxy in `vite.config.ts` already routes frontend `fetch('/api/...')` calls to this backend, but the CORS middleware is a useful safety net during development and stays out of the way in production. See [Tenant Mapping](/cloud/guides/cloud-apps/app-token-authentication#tenant-mapping) for more on managing tenants in production. ## 8. Add Run Scripts Open `backend/package.json` and replace the `scripts` block: ```json theme={null} "scripts": { "dev": "tsx watch --env-file=.env src/server.ts", "build": "tsc", "start": "node --env-file=.env dist/server.js" } ``` The `dev` script uses `tsx watch` to run TypeScript directly, restarting the server when any source file changes. The `--env-file=.env` flag loads environment variables natively without needing `dotenv`. The `build` and `start` scripts compile to JavaScript and run the compiled output for production. Also update the `"type": "commonjs"` to `"type": "module"` below the `scripts` in the `package.json` file so that Node can treat `.js` files as ES modules. ## 9. Run the Backend Start the dev server: ```bash theme={null} npm run dev ``` You should see: ``` Backend listening on http://localhost:5273 ``` In a second terminal, send a request with a fake app token to confirm the route is reachable: ```bash theme={null} curl http://localhost:5273/api/connect-tenant \ -H "Authorization: Bearer fake-token" ``` You should get back a `401` response with `{"error":"Failed to verify app token"}`. A real app token from the App Shell will follow the same path and succeed. ## Common Issues > [accordion] 'Cannot find module ./jtl-auth.js' or similar import error > > This error usually means TypeScript and Node are resolving modules differently. > > With `"type": "module"` in `package.json` and `"module": "NodeNext"` in `tsconfig.json`, Node expects ES module imports to include file extensions. Even if your source file is `jtl-auth.ts`, the import must use `./jtl-auth.js`. > > TypeScript resolves this correctly during development, and Node finds the compiled `.js` file at runtime. > > If you prefer not to use `.js` extensions, switch to `"module": "CommonJS"` in `tsconfig.json` and remove `"type": "module"` from `package.json`. > [accordion] 'CLIENT_ID and CLIENT_SECRET must be defined in .env' > > This means the backend started without loading your environment variables. > > The most common cause is running Node without the `--env-file=.env` flag. In that case, the `.env` file exists but is never read. > > The `dev` and `start` scripts already include this flag. If you're running the server manually, add it back or use `npm run dev`. > > Also confirm that the `.env` file is inside the `backend/` directory. The path is resolved relative to where Node is executed. > [accordion] 'Failed to fetch JWT (401)' from the auth endpoint > > A 401 from the auth endpoint means the credentials are not valid. > > If you are still using placeholder values, this is expected. Real credentials are provided after registering your app in the Partner Portal. > > If you have already registered: > > * check for typos or extra spaces in `.env` > * restart the dev server after making changes > > Environment variables are only read at startup, so updates to `.env` require a restart. > [accordion] 'Failed to verify app token' with real credentials > > Verification checks four things, and the audience check is the one most often wrong. `JTL_APP_ID` is the app ID shown in the Partner Portal under your app, not the client ID. > > If the audience is correct, confirm `JTL_ISSUER` matches the environment your app is registered in. A token issued by one environment does not verify against another's keys. > > App tokens are also valid for about an hour, so a token captured earlier during debugging will fail. > [accordion] CORS error in the browser console > > This means the browser blocked the response due to an origin mismatch. > > The backend allows requests from `http://localhost:5173`, which is the default Vite dev server port. If Vite runs on a different port (for example, 5174), the request will be rejected. > > Update the `origin` in `server.ts` to match the actual port, or restart Vite on 5173. > > If you're using the Vite dev proxy for `/api/*`, CORS should not appear. Seeing this error usually means the request is being made directly to the backend instead of going through the proxy. ## Next: Connect and Fetch Data The backend verifies app tokens and is ready to call the JTL Cloud API. The remaining work is registering your app with JTL to get real credentials, installing the app in the JTL Hub, and pulling product data from JTL-Wawi: > [card] [Connect and Fetch Data](/cloud/get-started/quick-start/from-scratch/connect-and-fetch) > > Register your app, install it in the JTL Hub, and fetch products from > JTL-Wawi. # PHP Source: https://developer.jtl-software.com/cloud/get-started/quick-start/from-scratch/backend-php Build the Slim backend for your JTL Cloud App. Verify app tokens, fetch access tokens, and proxy requests to the JTL Cloud API. Build the Slim 4 backend for a JTL Cloud App using PHP 8 and `firebase/php-jwt` for app token verification. By the end, the backend runs locally and the frontend's "Connecting to JTL Platform…" placeholder turns into a real connection. **Stack:** PHP 8.1+, Slim 4, Guzzle for HTTP requests, `vlucas/phpdotenv` for environment variables, `firebase/php-jwt` for JWT verification. ## Prerequisites You need: * ✅ **A finished frontend** from the [Build the Frontend](/cloud/get-started/quick-start/from-scratch/frontend) page, running locally on `http://localhost:5173` * ✅ **[PHP](https://www.php.net/downloads) 8.1 or higher**. Run `php --version` to check. * ✅ **[Composer](https://getcomposer.org/)** for dependency management. Run `composer --version` to check. ## What you're Building During setup, your backend verifies that the app token from your frontend is valid and was issued by JTL for your app. To do this: * Your backend fetches the identity provider's public keys (JWKS) * Verifies the token's signature, issuer, and expiry against them * Confirms the token's audience is your app, so a token minted for another app is rejected ```mermaid theme={null} sequenceDiagram participant FE as Your Frontend participant BE as Your Backend (Slim) participant IDP as JTL Identity Provider FE->>BE: GET /api/connect-tenant (Bearer app token) BE->>IDP: GET /oauth/v2/keys IDP-->>BE: Public keys (JWKS) BE->>BE: Verify signature, issuer, expiry, audience BE-->>FE: Verified tenant info ``` Once verified, the token tells your backend which tenant (merchant) and user is using your app. Your backend can then make tenant-scoped requests to the JTL Cloud API on their behalf, authenticating with its own client credentials. ## 1. Set up the Project Create a `backend` folder alongside the existing `frontend` folder, then initialise a Composer project inside it. ```bash theme={null} cd my-jtl-app mkdir backend cd backend composer init --name="my-jtl-app/backend" --type=project --no-interaction ``` Your project structure now looks like this: ``` my-jtl-app/ ├── frontend/ # From the previous page └── backend/ # New ``` ## 2. Install Packages ```bash theme={null} composer require slim/slim slim/psr7 guzzlehttp/guzzle vlucas/phpdotenv firebase/php-jwt ``` | Package | Purpose | | - | - | | `slim/slim` | The Slim 4 micro-framework: routing, request and response handling | | `slim/psr7` | The PSR-7 implementation Slim uses by default | | `guzzlehttp/guzzle` | HTTP client for making requests to JTL APIs | | `vlucas/phpdotenv` | Loads environment variables from a `.env` file | | `firebase/php-jwt` | Parses the JWKS and verifies app token signatures | ## 3. Set up Environment Variables Create `backend/.env`: ```dotenv theme={null} CLIENT_ID=your-client-id-here CLIENT_SECRET=your-client-secret-here JTL_APP_ID=your-app-id-here JTL_ISSUER=https://id.jtl-cloud.com PORT=5273 ``` The frontend's Vite dev proxy is already configured to forward `/api/*` requests to `localhost:5273`, so the `PORT` value matches that target. `JTL_APP_ID` is your app's ID, which an app token's audience must contain. `JTL_ISSUER` is the identity provider that issues app tokens. Add `.env` and `vendor/` to `backend/.gitignore` so secrets and dependencies don't end up in version control: ``` vendor .env ``` ## 4. Build the Auth Helper The first piece of the backend is a function that authenticates with JTL using your client credentials and returns an access token. Your backend uses it to make tenant-scoped calls to the JTL Cloud API. Create `backend/src/JtlAuth.php`: ```php theme={null} cachedToken !== null && time() < $this->tokenExpiresAt) { return $this->cachedToken; } if (empty($this->clientId) || empty($this->clientSecret)) { throw new \RuntimeException('CLIENT_ID and CLIENT_SECRET must be defined in .env'); } $authString = base64_encode("{$this->clientId}:{$this->clientSecret}"); $response = $this->httpClient->request('POST', self::AUTH_ENDPOINT, [ 'http_errors' => false, 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', 'Authorization' => "Basic {$authString}", ], 'form_params' => [ 'grant_type' => 'client_credentials', 'scope' => self::TOKEN_SCOPE, ], ]); $statusCode = $response->getStatusCode(); $body = $response->getBody()->getContents(); if ($statusCode < 200 || $statusCode >= 300) { throw new \RuntimeException("Failed to fetch JWT ({$statusCode}): {$body}"); } $data = json_decode($body, true); $expiresIn = $data['expires_in'] ?? 3599; $this->cachedToken = $data['access_token']; $this->tokenExpiresAt = time() + $expiresIn - 30; return $this->cachedToken; } } ``` The credentials are Base64-encoded and sent as a `client_credentials` grant to JTL's auth endpoint. The access token is cached in memory until 30 seconds before expiry, so repeat calls within the same request reuse it. ## 5. Build the Token Verifier The backend verifies the app token before trusting anything in it. `firebase/php-jwt` parses the identity provider's key set and selects the key matching the token's `kid`. Create `backend/src/AppTokenVerifier.php`: ```php theme={null} getKeys()); if (($claims['iss'] ?? null) !== $this->issuer) { throw new \RuntimeException('Token issuer does not match.'); } if (!isset($claims['exp'])) { throw new \RuntimeException('Token has no expiry.'); } $audience = (array) ($claims['aud'] ?? []); if (!in_array($this->appId, $audience, true)) { throw new \RuntimeException('Token audience does not contain this app.'); } $appIdClaim = $claims['urn:jtl:app_id'] ?? null; if ($appIdClaim !== null && $appIdClaim !== $this->appId) { throw new \RuntimeException('Token was minted for a different app.'); } return $claims; } private function getKeys(): array { if ($this->keys !== null) { return $this->keys; } $response = $this->httpClient->request('GET', "{$this->issuer}/oauth/v2/keys", [ 'http_errors' => false, 'headers' => ['Accept' => 'application/json'], ]); $statusCode = $response->getStatusCode(); if ($statusCode < 200 || $statusCode >= 300) { throw new \RuntimeException("Failed to fetch JWKS ({$statusCode})"); } $jwks = json_decode($response->getBody()->getContents(), true); return $this->keys = JWK::parseKeySet($jwks); } } ``` `JWT::decode` verifies the signature against the key whose `kid` matches the token header, and checks the expiry. The issuer and audience checks are separate because the library does not enforce them. The `urn:jtl:app_id` claim is optional. When absent the token is valid for your app, and when present it must equal your app ID. The key set is fetched on first use and held on the instance, so repeat verifications within the same request do not refetch. For cross-request reuse, swap the in-memory cache for APCu or another shared cache. ## 6. Build the Connect Tenant Endpoint Now connect the verifier into a Slim route. The frontend's shell layout sends the app token to the backend as a Bearer token. Create `backend/public/index.php`: ```php theme={null} load(); $httpClient = new Client(); $auth = new JtlAuth($_ENV['CLIENT_ID'] ?? '', $_ENV['CLIENT_SECRET'] ?? '', $httpClient); $verifier = new AppTokenVerifier( rtrim($_ENV['JTL_ISSUER'] ?? 'https://id.jtl-cloud.com', '/'), trim($_ENV['JTL_APP_ID'] ?? ''), $httpClient, ); $app = AppFactory::create(); $app->addBodyParsingMiddleware(); // Allow the Vite dev server to call the API during development $app->add(function (Request $request, $handler) { $response = $handler->handle($request); return $response ->withHeader('Access-Control-Allow-Origin', 'http://localhost:5173') ->withHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type') ->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); }); $app->options('/{routes:.+}', fn(Request $req, Response $res) => $res); $app->get('/api/connect-tenant', function (Request $request, Response $response) use ($verifier) { $authHeader = $request->getHeaderLine('Authorization'); $token = str_starts_with($authHeader, 'Bearer ') ? substr($authHeader, 7) : ''; if ($token === '') { $response->getBody()->write(json_encode(['error' => 'App token is required'])); return $response->withStatus(400)->withHeader('Content-Type', 'application/json'); } try { $claims = $verifier->verify($token); $tenantId = $claims['urn:jtl:tenant_id'] ?? null; if (!is_string($tenantId)) { $response->getBody()->write(json_encode(['error' => 'App token has no tenant claim'])); return $response->withStatus(400)->withHeader('Content-Type', 'application/json'); } // In a production app, you'd store the tenant connection in your database here $response->getBody()->write(json_encode([ 'success' => true, 'tenantId' => $tenantId, 'clientId' => $claims['client_id'] ?? null, ])); return $response->withHeader('Content-Type', 'application/json'); } catch (\Throwable $e) { $response->getBody()->write(json_encode(['error' => 'Failed to verify app token'])); return $response->withStatus(401)->withHeader('Content-Type', 'application/json'); } }); $app->run(); ``` The bootstrap loads `.env`, instantiates `JtlAuth` with the credentials and `AppTokenVerifier` with the issuer and app ID. Both instances are then captured by the route closure via `use ($verifier)` and shared across requests. The CORS middleware allows requests from the Vite dev server on port 5173. The dev proxy in `vite.config.ts` already routes frontend `fetch('/api/...')` calls to this backend, but the CORS headers are a useful safety net during development. See [Tenant Mapping](/cloud/guides/cloud-apps/app-token-authentication#tenant-mapping) for more on managing tenants in production. ## 7. Configure Composer Autoloading Open `backend/composer.json` and add a `psr-4` autoload mapping for the `App\` namespace: ```json theme={null} { "name": "my-jtl-app/backend", "type": "project", "require": { "slim/slim": "^4.15", "slim/psr7": "^1.7", "guzzlehttp/guzzle": "^7.9", "vlucas/phpdotenv": "^5.6", "firebase/php-jwt": "^6.10" }, "autoload": { "psr-4": { "App\\": "src/" } } } ``` Then regenerate the autoloader so Composer picks up the new mapping: ```bash theme={null} composer dump-autoload ``` This tells Composer that any class in the `App\` namespace lives under the `src/` directory, which is how `JtlAuth` and `SessionVerifier` get loaded when `index.php` references them. ## 8. Run the Backend Start the dev server: ```bash theme={null} php -S localhost:5273 -t public ``` You should see: ``` PHP 8.x.x Development Server (http://localhost:5273) started ``` In a second terminal, send a request with a fake app token to confirm the route is reachable: ```bash theme={null} curl http://localhost:5273/api/connect-tenant \ -H "Authorization: Bearer fake-token" ``` You should get back a `401` response with `{"error":"Failed to verify app token"}`. That's the expected outcome for an invalid token. A real app token from the App Shell will follow the same path and succeed. ## Common Issues > [accordion] 'Class App\JtlAuth not found' or similar autoload error > > This error means Composer's autoloader doesn't know where to find the class. The most common cause is forgetting to regenerate the autoload files after adding the `psr-4` mapping to `composer.json`. > > Running `composer dump-autoload` from the `backend/` directory rebuilds `vendor/autoload.php` to include any new namespace mappings. The error should clear after the next request. > [accordion] 'CLIENT_ID and CLIENT_SECRET must be defined in .env' > > This error means the backend started but couldn't find your credentials in the environment. The most common cause is that `.env` is sitting in the wrong directory, or that the `Dotenv::createImmutable()` call is pointing at the wrong path. > [accordion] 'Failed to verify app token' with real credentials > > Verification checks the signature, issuer, expiry, and audience. The audience check is the one most often wrong: `JTL_APP_ID` is the app ID shown in the Partner Portal under your app, not the client ID. > > If the audience is correct, confirm `JTL_ISSUER` matches the environment your app is registered in. A token issued by one environment does not verify against another's keys. > > App tokens are valid for about an hour, so a token captured earlier during debugging will fail on expiry. > [accordion] 'Failed to fetch JWT (401)' from the auth endpoint > > A 401 from the auth endpoint means the credentials are not valid. > > If you are still using placeholder values, this is expected. Real credentials are provided after registering your app in the Partner Portal. > > If you have already registered: > > * check for typos or extra spaces in `.env` > * restart the dev server after making changes > > Environment variables are only read at startup, so updates to `.env` require a restart. > [accordion] CORS error in the browser console > > A CORS error usually means the request reached the backend but the browser blocked the response because the origin didn't match what the backend allows. The CORS middleware in `index.php` is configured to allow `http://localhost:5173`, which matches the default Vite dev server port. > > If the Vite dev server is running on a different port (for example, because port 5173 was already in use and Vite picked 5174 instead), the browser will see a mismatch. Updating the `Access-Control-Allow-Origin` value in `index.php` to match the actual Vite port, or freeing up port 5173, should resolve it. ## Next: Connect and Fetch Data The backend verifies app tokens and is ready to call the JTL Cloud API. The remaining work is registering your app with JTL to get real credentials, installing the app in the JTL Hub, and pulling product data from JTL-Wawi: > [card] [Connect and Fetch Data](/cloud/get-started/quick-start/from-scratch/connect-and-fetch) > > Register your app, install it in the JTL Hub, and fetch products from > JTL-Wawi. # Connect and Fetch Data Source: https://developer.jtl-software.com/cloud/get-started/quick-start/from-scratch/connect-and-fetch Register your app with JTL, install it in the JTL Hub, and fetch real product data from JTL-Wawi. Bring everything together. Register your app with JTL to get real credentials, install it in the JTL Hub, then add an items endpoint to your backend and a product table to your frontend. ## Prerequisites You need: * ✅ **A finished frontend** from the [Build the Frontend](/cloud/get-started/quick-start/from-scratch/frontend) guide * ✅ **A finished backend** from either the [Node.js](/cloud/get-started/quick-start/from-scratch/backend-node), [C#](/cloud/get-started/quick-start/from-scratch/backend-csharp), or [PHP](/cloud/get-started/quick-start/from-scratch/backend-php) guide * ✅ **A JTL ID** (your login to the JTL ecosystem) * ✅ **Access to an organization (tenant) in the [Partner Portal](https://partner.jtl-cloud.com)** (created automatically on first login if you don’t have one yet) * ✅ **[JTL-Wawi](https://www.jtl-software.com/de/warenwirtschaftssystem-software/jtl-wawi-download)** installed and running locally, with at least one product, and connected to JTL Cloud. If you don’t have JTL Cloud set up yet, follow the step-by-step guide: [Create a Developer Account](/cloud/get-started/create-developer-account). ## What you're Building So far, the frontend and backend are only loosely connected. The frontend can render the app, and the backend can verify authentication tokens, but neither side is yet tied to a real merchant installation. This guide closes the loop. ```mermaid theme={null} sequenceDiagram participant Dev as You participant Portal as Partner Portal participant Hub as JTL Hub participant App as Your App participant Wawi as JTL-Wawi Dev->>Portal: Register app with manifest Portal-->>Dev: Client ID + Client Secret Dev->>Hub: Install app in test tenant Hub->>App: Loads /setup in iframe App->>App: Verifies app token, completes handshake Dev->>App: Opens /erp menu item App->>Wawi: GET /api/items (with app token) Wawi-->>App: Product data ``` By the end, opening the app from the Cloud ERP menu will show a table of real products from JTL-Wawi. ## 1. Create the Manifest Your app's manifest declares how it integrates with JTL: the URLs it exposes and its Cloud ERP menu items. Create an `app.json` file in the backend directory: ```json theme={null} { "version": "1.0.0", "technicalName": "my-jtl-app", "lifecycle": { "configurationUrl": "http://localhost:5173/setup" }, "authentication": { "serviceAccount": { "clientCredentials": true, "description": "Reads items from the JTL API" } }, "capabilities": { "hub": { "appLauncher": { "redirectUrl": "http://localhost:5173/hub" } }, "erp": { "api": { "scopes": ["items.read"] }, "menuItems": [ { "id": "my-jtl-app-menu", "name": "My JTL App", "url": "http://localhost:5173/erp" } ] } } } ``` Three of the URLs map directly to the three frontend routes you built: | Manifest field | Page in your code | | - | - | | `lifecycle.configurationUrl` | `_shell.setup.tsx` | | `capabilities.hub.appLauncher.redirectUrl` | `hub.tsx` | | `capabilities.erp.menuItems[].url` | `_shell.erp.tsx` | For the full field reference, see the [App Manifest](/cloud/guides/cloud-apps/app-manifest). > [!TIP] > > The example uses `http://localhost:5173/...`. When you deploy, replace these with your production domain. All URLs must be publicly reachable. `localhost` works only because the JTL App Shell runs in your browser, not on JTL's servers. ## 2. Register your App Register your app with the manifest you just created. Both paths produce the same app. > [tab] CLI > > With your manifest saved as `app.json` in your project root, run the CLI: > > ```bash theme={null} > npx -y @jtl-software/create-cloud-app@latest register > ``` > > The CLI signs you in with your JTL ID, lets you select a tenant, and registers the app from your `app.json`. It then writes your client ID, app ID, and client secret to a `.env` file in your project. > [tab] Registration Wizard > > In the [Partner Portal](https://partner.jtl-cloud.com/), open **Manage apps** and click **Create** to open the app creation wizard. It walks through five steps: Basics, The integration, API permissions, Authentication, and Summary. > > > [!TIP] > > > > Already have your `app.json`? Select **JSON Code Editor**, paste it, and save. The form populates with your values, and you continue from the Summary step to review and create the app. > > **1. Basics** > > Enter the **Internal app name** used to identify the app (it is not shown to customers) and the **App-Version** in `major.minor.patch` format, for example `1.0.0`. Click **Continue**. > > ![App registration - Basics](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/wizard_basics.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=62c7bf3baa643f8bdc20bc12a06e6aca) > > **2. The integration** > > Enter the URLs that connect your app to JTL: > > * **Configuration URL**: the setup entry point JTL calls when a merchant installs your app. Use `http://localhost:5173/setup`, which maps to your `_shell.setup.tsx` route. > * **App-Card-URL**: the URL opened from the app card in JTL Hub after setup completes. Use `http://localhost:5173/hub`, which maps to your `hub.tsx` route. > > Under **Possible integration into Cloud ERP**, select **Add menu item** and add one item pointing to `http://localhost:5173/erp`, which maps to your `_shell.erp.tsx` route. This is the entry the merchant clicks in the ERP sidebar to open your app. > > Click **Continue**. > > ![App registration - Integration](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/wizard_integration.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=b8f23f54420e51bd2708718f8729be71) > > **3. API permissions** > > Select the API permissions your app needs. For this guide, the app reads product data, so the items read scope is sufficient. Use the search field to find and select it, then click **Continue**. > > > [!NOTE] > > > > Declared scopes are enforced at the API layer on JTL-Wawi 2.2.0 and higher. Declare the scopes your app actually uses. > > ![App registration - Permissions](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/wizard_permissions.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=d1adca2a278e426abfc68d6707b8ca10) > > **4. Authentication** > > Select the authentication method for your app. Choose **Service account (server-to-server)** since your app will talk to JTL using the backend. > > > [!TIP] > > > > For app that don't have a backend, choose **Public client (user login)**. See [Standalone Authentication](/cloud/guides/cloud-apps/standalone-authentication) for more details. > > ![App registration - Authentication](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/wizard_authentication.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=23478562d690f99cd06802bc0c5c00da) > > **5. Summary** > > Review the configuration. Each section has an edit control if you need to change a value. When everything is correct, create the app. > > **6. Copy your credentials** > > After the app is created, you'll see your **Client ID** and **Service Account Secret Key**. Your **App ID** is the Client ID without the `app-` prefix. For example if your Client ID is `app-1234-5678`, your App ID is `1234-5678`. > > > [!WARNING] > > > > The Service Account Secret Key is shown only once. Copy the value immediately. If you lose it, you'll need to register a new app. > [!WARNING] > > **Don't commit your environment files.** They contain your client secrets. The CLI writes them to paths that the template's `.gitignore` already excludes, but verify this before pushing to a shared repository. ## 3. Update your Backend Credentials Replace the placeholder values you set earlier with the real Client ID and Client Secret. > [tab] Node.js > > Open `backend/.env` and replace the placeholder values: > > ```dotenv theme={null} > CLIENT_ID=your-actual-client-id > CLIENT_SECRET=your-actual-client-secret > JTL_APP_ID=your-actual-app-id > JTL_ISSUER=https://id.jtl-cloud.com > PORT=5273 > ``` > > The `tsx watch` command picks up source file changes automatically, but environment variables are read once at startup. Stop and restart the backend to pick up the new values. > [tab] C# > > From the `Backend/` directory, update the user-secrets values: > > ```bash theme={null} > dotnet user-secrets set "Jtl:ClientId" "your-actual-client-id" > dotnet user-secrets set "Jtl:ClientSecret" "your-actual-client-secret" > dotnet user-secrets set "Jtl:AppId" "your-actual-app-id" > ``` > > ASP.NET Core reads configuration once at startup. Stop and restart the backend to pick up the new values. > [tab] PHP > > Open `backend/.env` and replace the placeholder values: > > ```dotenv theme={null} > CLIENT_ID=your-actual-client-id > CLIENT_SECRET=your-actual-client-secret > JTL_APP_ID=your-actual-app-id > JTL_ISSUER=https://id.jtl-cloud.com > PORT=5273 > ``` > > PHP's built-in development server reads environment variables once at startup. Stop the server with `Ctrl+C` and start it again to pick up the new values. ## 4. Run Both Processes You need both the frontend and backend running. Open two terminals from the project root. **Terminal 1 (backend):** > [tab] Node.js > > ```bash theme={null} > cd backend > npm run dev > ``` > [tab] C# > > ```bash theme={null} > cd Backend > dotnet run > ``` > [tab] PHP > > ```bash theme={null} > cd backend > php -S localhost:5273 -t public > ``` **Terminal 2 (frontend):** ```bash theme={null} cd frontend npm run dev ``` Opening `http://localhost:5173` directly in a browser will show a blank page or the placeholder error state. The app is meant to be rendered inside the JTL App Shell, which is what the next step covers. ## 5. Install the App in JTL Hub **1. Open JTL Hub** Go to [JTL Hub](https://hub.jtl-cloud.com/) and log in. **2. Find your App** Navigate to the **Manage apps** menu and click the **Apps in development** tab. You should see your newly registered app. ![Discover apps](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/verify_app.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=6d9ee8197459598a2f21099d7bbaa764) **3. Install the App** Once the app is installed, you'll see a success screen with the option to configure the app. Click the **Configure app** button to proceed to the next step. ![Install app on JTL](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/install_on_JTL.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=d6e18236f22efc7814beec19d10ddf79) **4. Complete the Setup** On the configuration page, you'll see the tenant ID your app is linked to alongside the **Complete Setup** button. Click the **Complete Setup** button on your setup page. This triggers the full setup handshake between your app and JTL. ![Installation complete](https://mintcdn.com/jtlsoftwaregmbh/IxYp0dsX_we5vpPI/images/with_tenant_ID.png?fit=max\&auto=format\&n=IxYp0dsX_we5vpPI\&q=85\&s=7c0c04fd77ee62c9f7b792089aabd075) This means the App Shell recognizes the installation as complete. ## 6. Add an Items Endpoint The backend can now make tenant-scoped calls to the JTL Cloud API. The next step is adding an endpoint that fetches products from JTL-Wawi via GraphQL. > [!NOTE] > > Every API request that accesses tenant data needs an `X-Tenant-ID` header. > The backend reads this value from the `urn:jtl:tenant_id` claim of the > verified app token. See [App Token > Authentication](/cloud/guides/cloud-apps/app-token-authentication) for the > full claim list. > [tab] Node.js > > Add the items route to `backend/src/server.ts`. Place it alongside the existing `connect-tenant` route: > > ```typescript theme={null} > import { getJwt } from './jtl-auth.js'; > > app.get('/api/items', async (req: Request, res: Response) => { > const authHeader = req.header('authorization'); > if (!authHeader?.startsWith('Bearer ')) { > return res > .status(401) > .json({ error: 'Missing or invalid Authorization header' }); > } > > const token = authHeader.slice(7); > > try { > const claims = await verify(token); > const tenantId = claims['urn:jtl:tenant_id']; > > if (typeof tenantId !== 'string') { > return res.status(400).json({ error: 'App token has no tenant claim' }); > } > > const accessToken = await getJwt(); > > const response = await fetch( > 'https://api.jtl-cloud.com/erp/v2/graphql', > { > method: 'POST', > headers: { > 'Content-Type': 'application/json', > Authorization: `Bearer ${accessToken}`, > 'X-Tenant-ID': tenantId, > }, > body: JSON.stringify({ > operationName: 'GetERPItems', > query: ` > query GetERPItems { > QueryItems(first: 10) { > nodes { id sku name notes basePriceUnit } > totalCount > } > } > `, > }), > }, > ); > > const body = await response.json(); > return res.json(body); > } catch (error) { > return res.status(500).json({ error: 'Failed to fetch items' }); > } > }); > ``` > > The route reads the app token from the `Authorization` header, verifies it to read the tenant from its claims, fetches an access token, and forwards the GraphQL response back to the frontend as-is. > [tab] C# > > Create `Backend/Controllers/ItemsController.cs`: > > ```csharp theme={null} > using System.Net.Http.Headers; > using System.Text; > using Backend.Services; > using Microsoft.AspNetCore.Mvc; > > namespace Backend.Controllers; > > [ApiController] > [Route("api/items")] > public class ItemsController : ControllerBase > { > private readonly HttpClient _http; > private readonly JtlAuthService _auth; > private readonly AppTokenVerifier _verifier; > > public ItemsController( > IHttpClientFactory httpFactory, > JtlAuthService auth, > AppTokenVerifier verifier) > { > _http = httpFactory.CreateClient(); > _auth = auth; > _verifier = verifier; > } > > [HttpGet] > public async Task Get() > { > var authHeader = Request.Headers.Authorization.ToString(); > if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer ")) > { > return Unauthorized(new { error = "Missing or invalid Authorization header" }); > } > > var token = authHeader.Substring("Bearer ".Length); > > try > { > var jwt = await _verifier.VerifyAsync(token); > var tenantId = jwt.Claims > .FirstOrDefault(c => c.Type == "urn:jtl:tenant_id")?.Value; > > if (string.IsNullOrEmpty(tenantId)) > { > return BadRequest(new { error = "App token has no tenant claim" }); > } > > var accessToken = await _auth.GetJwtAsync(); > > var query = """ > { > "operationName": "GetERPItems", > "query": "query GetERPItems { QueryItems(first: 10) { nodes { id sku name notes basePriceUnit } totalCount } }" > } > """; > > var request = new HttpRequestMessage( > HttpMethod.Post, > $"{_auth.ApiBaseUrl}/erp/v2/graphql"); > request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); > request.Headers.Add("X-Tenant-ID", tenantId); > request.Content = new StringContent(query, Encoding.UTF8); > request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); > > var response = await _http.SendAsync(request); > var body = await response.Content.ReadAsStringAsync(); > > return new ContentResult > { > Content = body, > ContentType = "application/json", > StatusCode = (int)response.StatusCode, > }; > } > catch (Exception ex) > { > Console.Error.WriteLine($"Error in /api/items route: {ex}"); > return StatusCode(500, new > { > error = "Failed to fetch items", > message = ex.Message, > }); > } > } > } > ``` > > The controller reads the app token from the `Authorization` header (sent by the frontend as a `Bearer` token), verifies it to extract the tenant ID, fetches a fresh access token, and forwards the GraphQL response back to the frontend as-is. > > The existing `app.MapControllers()` call in `Program.cs` already discovers this controller, so no extra registration is needed. > [tab] PHP > > Add the items route to `backend/public/index.php`. Place it alongside the existing `connect-tenant` route: > > ```php theme={null} > $app->get('/api/items', function (Request $request, Response $response) use ($auth, $verifier, $httpClient) { > $authHeader = $request->getHeaderLine('Authorization'); > if (!str_starts_with($authHeader, 'Bearer ')) { > $response->getBody()->write(json_encode(['error' => 'Missing or invalid Authorization header'])); > return $response->withStatus(401)->withHeader('Content-Type', 'application/json'); > } > > $token = substr($authHeader, 7); > > try { > $claims = $verifier->verify($token); > $tenantId = $claims['urn:jtl:tenant_id'] ?? null; > > if (!is_string($tenantId)) { > $response->getBody()->write(json_encode(['error' => 'App token has no tenant claim'])); > return $response->withStatus(400)->withHeader('Content-Type', 'application/json'); > } > > $accessToken = $auth->getJwt(); > > $apiResponse = $httpClient->request('POST', JtlAuth::API_BASE_URL . '/erp/v2/graphql', [ > 'http_errors' => false, > 'headers' => [ > 'Content-Type' => 'application/json', > 'Accept' => 'application/json', > 'Authorization' => "Bearer {$accessToken}", > 'X-Tenant-ID' => $tenantId, > ], > 'json' => [ > 'operationName' => 'GetERPItems', > 'query' => 'query GetERPItems { QueryItems(first: 10) { nodes { id sku name notes basePriceUnit } totalCount } }', > ], > ]); > > $body = $apiResponse->getBody()->getContents(); > > $response->getBody()->write($body); > return $response->withHeader('Content-Type', 'application/json'); > } catch (\Throwable $e) { > error_log("Failed to fetch items: {$e->getMessage()}"); > $response->getBody()->write(json_encode(['error' => 'Failed to fetch items'])); > return $response->withStatus(500)->withHeader('Content-Type', 'application/json'); > } > }); > ``` > > The route reads the app token from the `Authorization` header (sent by the frontend as a `Bearer` token), verifies it to extract the tenant ID, fetches a fresh access token, and forwards the GraphQL response back to the frontend as-is. ## 7. Display Items in the ERP Page Replace `frontend/src/routes/_shell.erp.tsx` with a version that fetches and renders the products: ```tsx theme={null} import { createFileRoute } from '@tanstack/react-router'; import { Box, Text } from '@jtl-software/platform-ui-react'; import { useCallback, useEffect, useState } from 'react'; import { useAppBridge } from '../appBridge'; interface Item { id: string; sku: string; name: string; } interface ItemsResponse { data: { QueryItems: { nodes: Item[]; totalCount: number; }; }; } function ErpPage() { const { appBridge } = useAppBridge(); const [items, setItems] = useState([]); const [totalCount, setTotalCount] = useState(0); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const fetchItems = useCallback(async () => { if (!appBridge) return; try { setLoading(true); const { accessToken } = await appBridge.method.call<{ accessToken: string; }>('getAppToken'); const res = await fetch('/api/items', { headers: { Authorization: `Bearer ${accessToken}` }, }); if (!res.ok) { throw new Error(`Request failed (${res.status})`); } const data: ItemsResponse = await res.json(); setItems(data.data.QueryItems.nodes || []); setTotalCount(data.data.QueryItems.totalCount || 0); } catch (err) { setError( err instanceof Error ? err.message : 'Failed to load products', ); } finally { setLoading(false); } }, [appBridge]); useEffect(() => { fetchItems(); }, [fetchItems]); if (error) { return ( Error {error} ); } return ( My JTL Cloud App Products from Cloud-ERP {loading ? ( Loading products... ) : items.length === 0 ? ( No products found. Make sure your test account has items in Cloud-ERP. ) : ( <> Showing {items.length} of {totalCount} products {items.map((item) => ( ))}
sku name
{item.sku} {item.name}
)}
); } export const Route = createFileRoute('/_shell/erp')({ component: ErpPage, }); ``` On mount, the component requests an app token from the AppBridge, sends it to your backend as a Bearer token, and renders the returned products in a table. The round-trip means the backend always knows which tenant the request belongs to, without the frontend ever telling it. A sample response from the GraphQL API looks like this: ```json theme={null} { "data": { "QueryItems": { "nodes": [ { "id": "895d2d4d-4ed4-44c7-ac61-ebec01000000", "sku": "AR2016041-VKO", "name": "Men's T-shirt" }, { "id": "895d2d4d-4ed4-44c7-ac61-ebec06000000", "sku": "AR2016041-002", "name": "Men's T-shirt orange S" } ], "totalCount": 674 } } } ``` ## 8. Open the App from the ERP Menu In the [Cloud ERP](https://erp.jtl-cloud.com), navigate to the **App** menu and find the **My JTL App** menu item that the manifest registered. Clicking it loads `/erp` inside the App Shell. You should see a header reading **My JTL Cloud App**, the connected tenant ID, and a table listing the first ten products from your JTL-Wawi instance. This completes the full handshake flow: the App Shell loads your frontend in an iframe, AppBridge provides a short-lived app token, your backend verifies it and uses its own access token to make a tenant-scoped request to the JTL Cloud API, and the response is returned to the browser. ## Common Issues > [accordion] 'Cannot find module ./jtl-auth.js' or similar import error > > This error usually means TypeScript and Node are resolving modules differently. > > With `"type": "module"` in `package.json` and `"module": "NodeNext"` in `tsconfig.json`, Node expects ES module imports to include file extensions. Even if your source file is `jtl-auth.ts`, the import must use `./jtl-auth.js`. > > TypeScript resolves this correctly during development, and Node finds the compiled `.js` file at runtime. > > If you prefer not to use `.js` extensions, switch to `"module": "CommonJS"` in `tsconfig.json` and remove `"type": "module"` from `package.json`. > [accordion] 'CLIENT_ID and CLIENT_SECRET must be defined in .env' > > This means the backend started without loading your environment variables. > > The most common cause is running Node without the `--env-file=.env` flag. In that case, the `.env` file exists but is never read. > > The `dev` and `start` scripts already include this flag. If you're running the server manually, add it back or use `npm run dev`. > > Also confirm that the `.env` file is inside the `backend/` directory. The path is resolved relative to where Node is executed. > [accordion] 'Failed to fetch JWT (401)' from the auth endpoint > > A 401 from the auth endpoint means the credentials are not valid. > > If you are still using placeholder values, this is expected. Real credentials are provided after registering your app in the Partner Portal. > > If you have already registered: > > * check for typos or extra spaces in `.env` > * restart the dev server after making changes > > Environment variables are only read at startup, so updates to `.env` require a restart. > [accordion] The frontend can reach the backend but still shows 'Waiting for backend' > > This usually means the backend responded, but not with a successful (2xx) response. > > The frontend treats any non-2xx response as an error and shows the placeholder state. > > Open the browser console and inspect the `/api/connect-tenant` response: > > * a 401 is expected at this stage without real credentials > * a 500 or network error indicates a backend issue (check server logs) > > Once valid credentials are configured, this state resolves automatically. > [accordion] CORS error in the browser console > > This means the browser blocked the response due to an origin mismatch. > > The backend allows requests from `http://localhost:5173`, which is the default Vite dev server port. If Vite runs on a different port (for example, 5174), the request will be rejected. > > Update the `origin` in `server.ts` to match the actual port, or restart Vite on 5173. > > If you're using the Vite dev proxy for `/api/*`, CORS should not appear. Seeing this error usually means the request is being made directly to the backend instead of going through the proxy. ## What's Next? You've built a working JTL Cloud App from scratch: a frontend that runs inside the JTL App Shell, a backend that verifies app tokens and proxies requests to the JTL Cloud API, and a real connection to a tenant pulling live product data. Where to go from here: > [card] [Test your App](/cloud/get-started/test-your-app) > > Validate your app in the Cloud ERP with real data. > [card] [Using Platform APIs](/cloud/guides/cloud-apps/using-platform-apis) > > Use the JTL-Wawi REST and GraphQL APIs, handle responses, and work with > tenant-scoped data. > [card] [GraphQL Playground](/cloud/api-reference/graphql-playground) > > Try queries and mutations interactively against your ERP instance. > [card] [App Shell & UI](/cloud/guides/cloud-apps/app-shell-ui-integration) > > Learn how to integrate deeper with the JTL UI and App Shell. > [card] [Submit your App](/cloud/get-started/submitting-your-app/overview) > > Publish to the App Store, or share your app privately with activation codes. # Build the Frontend Source: https://developer.jtl-software.com/cloud/get-started/quick-start/from-scratch/frontend Scaffold the React frontend for your JTL Cloud App with TanStack Router and the JTL AppBridge SDK. Build the React frontend for a JTL Cloud App using Vite, TypeScript, [TanStack Router](https://tanstack.com/router/latest), and the JTL AppBridge SDK. By the end, the app runs locally with three working routes and a clear state for connecting to your backend. **Stack:** Vite, React, TypeScript, TanStack Router (file-based routing), JTL AppBridge, JTL Platform UI. ## Prerequisites You need: * ✅ **A JTL ID** (your login to the JTL ecosystem) * ✅ **Access to an organization (tenant) in the [Partner Portal](https://partner.jtl-cloud.com)** (created automatically on first login) * ✅ **[Node.js](https://nodejs.org/) v24.16.0 or higher** (current LTS, includes `npm`). Verify with `node --version` and `npm --version` If you don't have your JTL ID and Partner Portal access yet, follow [Create a Developer Account](/cloud/get-started/create-developer-account) first. ## What you're Building Before writing code, here’s how a JTL Cloud App works: ```mermaid theme={null} sequenceDiagram participant Shell as JTL App Shell participant FE as Your Frontend participant BE as Your Backend Shell->>FE: Loads app in iframe FE->>Shell: appBridge.method.call('getAppToken') Shell-->>FE: App token (JWT) FE->>BE: GET /api/connect-tenant (Bearer app token) BE-->>FE: Verified tenant info ``` Your frontend runs inside JTL’s App Shell (in an iframe). It communicates with the shell through **AppBridge**, a small SDK that exposes shell capabilities to the iframe. The most important one is `getAppToken`, a short-lived signed token that proves which merchant (tenant) is currently using your app. Your frontend sends that token to your backend, which verifies it and uses it to make tenant-scoped calls to the JTL API. Not every page in your app runs inside the shell. The frontend has three routes, and they fall into two groups: * `/setup` and `/erp` run inside the App Shell iframe. AppBridge is available, and the app knows which tenant it's serving. * `/hub` opens in a standalone browser tab when a merchant clicks the app card. There is no iframe, no AppBridge, and no tenant context. These two contexts require slightly different setup. You’ll handle that when building the frontend. > [!NOTE] > > Working with an AI coding tool? [Connect the JTL docs MCP server](/build-with-ai), > then paste the prompt below to scaffold the project before following the steps here. ```text icon="sparkles" AI Assistant Prompt theme={null} Help me build the frontend for a JTL Cloud App. Use the jtl-docs MCP server for any platform details. Scaffold a Vite, React, TypeScript project on port 5173 with TanStack Router file-based routing. Put the AppBridge provider behind a pathless _shell layout so /setup and /erp inherit it and /hub stays outside it. ``` ## 1. Create the Project ```bash theme={null} mkdir my-jtl-app cd my-jtl-app npm create vite@latest frontend -- --template react-ts ``` When prompted: * **Ok to proceed? (y):** `y` * **Install with npm and start now?:** `Yes` Once Vite finishes installing, press `Ctrl + C` to stop the dev server. ## 2. Install Packages ```bash theme={null} cd frontend npm install @tanstack/react-router @jtl-software/cloud-apps-core @jtl-software/platform-ui-react tailwindcss @tailwindcss/vite npm install -D @tanstack/router-plugin @tanstack/react-router-devtools ``` | Package | Purpose | | - | - | | `@tanstack/react-router` | Type-safe router with file-based routing | | `@tanstack/router-plugin` | Vite plugin that auto-generates the route tree from your file structure | | `@tanstack/react-router-devtools` | Devtools panel for inspecting routes (dev only) | | `@jtl-software/cloud-apps-core` | AppBridge SDK: communication between your app and the JTL App Shell | | `@jtl-software/platform-ui-react` | JTL's UI component library (Button, Card, Text, etc.) | | `tailwindcss` + `@tailwindcss/vite` | Utility-first CSS, required by the JTL UI library | ## 3. Configure Vite Replace `frontend/vite.config.ts`: ```typescript theme={null} import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import tailwindcss from '@tailwindcss/vite'; import { tanstackRouter } from '@tanstack/router-plugin/vite'; import path from 'path'; export default defineConfig({ server: { port: 5173, proxy: { '/api': { target: 'http://localhost:5273', changeOrigin: true, }, }, }, plugins: [ // The router plugin must come before the React plugin tanstackRouter({ target: 'react', autoCodeSplitting: true }), react(), tailwindcss(), ], resolve: { alias: { '/assets': path.join( path.dirname(require.resolve('@jtl-software/platform-ui-react')), 'assets', ), }, }, }); ``` This does three things: * **TanStack Router plugin** watches `src/routes/` and regenerates `src/routeTree.gen.ts` whenever you add or rename a route file. The plugin must be listed before `react()`. See the [installation docs](https://tanstack.com/router/latest/docs/installation/with-vite) for details. * **Tailwind plugin** enables Tailwind utilities, which the JTL UI library depends on. * **Dev proxy** forwards `/api/*` requests to a backend on `localhost:5273`. Your frontend can call `fetch('/api/...')` and Vite will route the request without CORS issues during development. ## 4. Set up Styles Replace `frontend/src/index.css`: ```css theme={null} @import '@jtl-software/platform-ui-react/index.css'; @import 'tailwindcss'; ``` ## 5. Create the Route Files TanStack Router uses file-based routing, so your folder structure under `src/routes/` *is* your route configuration. Delete the default `src/App.tsx` (the router replaces it), then create the following structure: ``` frontend/src/routes/ ├── __root.tsx # Root layout (devtools, outlet) ├── _shell.tsx # Pathless layout for routes that render inside the App Shell ├── _shell.setup.tsx # /setup (inside App Shell) ├── _shell.erp.tsx # /erp (inside App Shell) └── hub.tsx # /hub (standalone, no AppBridge) ``` Two conventions are in play here: * **`__root.tsx`** is the top-level layout, always rendered. * **`_shell.tsx`** is a [pathless layout route](https://tanstack.com/router/latest/docs/routing/routing-concepts#pathless-layout-routes). The leading underscore means it doesn't add a URL segment, so `_shell.setup.tsx` becomes `/setup`, not `/_shell/setup`. Any route file prefixed with `_shell.` shares the layout's wrapper. `hub.tsx` doesn't, so it bypasses the AppBridge initialization entirely. ### Root Route Add the following to your `frontend/src/routes/__root.tsx`: ```tsx theme={null} import { createRootRoute, Outlet } from '@tanstack/react-router'; import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'; export const Route = createRootRoute({ component: () => ( <> ), }); ``` The `` is where child routes render. During development, a devtools panel appears in the bottom corner. It won’t be included in your production build. ### Shell Layout (AppBridge Provider) First, create a `frontend/src/appBridge.tsx` file that initializes AppBridge once, exposes the bridge through React Context, and shows a loading state until the connection completes. ```tsx theme={null} import { createContext, useContext, useEffect, useState, type ReactNode, } from 'react'; import { createAppBridge, type AppBridge } from '@jtl-software/cloud-apps-core'; interface AppBridgeContextValue { appBridge: AppBridge | null; } const AppBridgeContext = createContext({ appBridge: null, }); export function useAppBridge() { return useContext(AppBridgeContext); } const bridgePromise = createAppBridge(); export function AppBridgeProvider({ children }: { children: ReactNode }) { const [appBridge, setAppBridge] = useState(null); useEffect(() => { let cancelled = false; bridgePromise.then(bridge => { if (cancelled) return; setAppBridge(bridge); }); return () => { cancelled = true; }; }, []); if (!appBridge) { return (

Connecting to JTL Platform...

); } return ( {children} ); } ``` Then, update the shell layout to wrap every iframe route. `frontend/src/routes/_shell.tsx`: ```tsx theme={null} import { createFileRoute, Outlet } from '@tanstack/react-router'; import { AppBridgeProvider } from '../appBridge'; function ShellLayout() { return ( ); } export const Route = createFileRoute('/_shell')({ component: ShellLayout, }); ``` ### Setup Page Add the following to your `frontend/src/routes/_shell.setup.tsx`: ```tsx theme={null} import { createFileRoute } from '@tanstack/react-router'; import { Button, Box, Text } from '@jtl-software/platform-ui-react'; import { useAppBridge } from '../appBridge'; import { useEffect, useState } from 'react'; function SetupPage() { const { appBridge } = useAppBridge(); const [tenantId, setTenantId] = useState(null); const [isReady, setIsReady] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (!appBridge) return; let cancelled = false; async function init() { try { const { accessToken } = await appBridge.method.call<{ accessToken: string; }>('getAppToken'); if (cancelled) return; const res = await fetch('/api/connect-tenant', { headers: { Authorization: `Bearer ${accessToken}` }, }); if (cancelled) return; if (!res.ok) { const data = await res.json().catch(() => null); throw new Error( data?.error || `Connect failed (${res.status})`, ); } const data = await res.json(); if (cancelled) return; setTenantId(data.tenantId); } catch (err) { if (cancelled) return; setError( err instanceof Error ? err.message : 'Failed to initialize', ); } finally { if (!cancelled) setIsReady(true); } } init(); return () => { cancelled = true; }; }, [appBridge]); const handleSetupCompleted = async () => { if (!appBridge) return; try { await appBridge.method.call('setupCompleted'); } catch (err) { console.error('Setup completion failed:', err); } }; if (!isReady) { return ( Linking your account... ); } return ( Connect to JTL Cloud {error || 'Your app has been verified and is ready to connect.'} {tenantId && ( Tenant:{' '} {tenantId} )}