Skip to content
Why Developers Choose OnlyOffice for Self-Hosted Document Editing

Why Developers Choose OnlyOffice for Self-Hosted Document Editing

This article explores OnlyOffice as a self-hosted document editing engine, detailing its API integration, private deployment via Docker, real-time collaboration, white-labeling options, and a complete Spring Boot integration guide with JWT-secured callbacks and versioned document storage.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech

Introduction

Enterprise projects often require in-browser Word editing so users don't have to download, edit, and re-upload files. Three constraints make this hard: private deployment (data cannot leave the intranet for state-owned or financial clients), embedding the editor inside the existing business system (not redirecting to a separate platform), and controllable development cost (commercial SDKs charge per seat; building a .docx renderer from scratch takes months). OnlyOffice solves all three.

What Is OnlyOffice?

OnlyOffice is a self-hosted online document editing engine that supports Word, Excel, PowerPoint, PDF, and forms. It is not a cloud drive or a collaboration platform; it is a "document editing capability" block that you embed via API. Your system still owns users, permissions, file storage, and business flows; OnlyOffice only renders the .docx in the browser, lets users edit, and notifies your backend to save the result.

Three editions exist: Community (free, AGPL v3, suitable for small teams and testing), Enterprise (commercial license, adds admin panel, advanced security, support), and Developer (commercial license, adds white-labeling — replace logo, theme colors, about page). Core editing features are identical across editions.

Four Developer-Relevant Capabilities

3.1 API Integration

The integration model has three steps: backend generates a config JSON, frontend loads the editor with that config, and the document service calls your callback URL to save.

Config mechanism : Your backend produces a JSON describing file type, document URL, permissions, user info, UI language, and callback URL. This JSON is the editor's "instruction manual."

Frontend loading : Place a <div>, include api.js, and call new DocsAPI.DocEditor("div-id", config). The editor renders inside that div.

Callback save : When the user finishes, OnlyOffice POSTs to your callbackUrl with a status code and a download URL. Your backend downloads the new file, overwrites storage, and returns success.

50+ connectors : Ready-made connectors for Nextcloud, Moodle, Odoo, WordPress, SharePoint, etc. But you can also ignore them and embed directly via the API; the connectors are essentially API usage examples.

3.2 Private Deployment

OnlyOffice runs on local servers, private clouds, or fully offline intranets. Official downloads include Windows/Linux packages and Docker images. The Enterprise edition explicitly states: self-hosted, data stays in your infrastructure, no third-party data access.

Fastest start with Docker:

docker run -i -t -d -p 8080:80 
  -e JWT_ENABLED=true 
  -e JWT_SECRET=susantest123456 
  -v /data/onlyoffice/data:/var/www/onlyoffice/Data 
  onlyoffice/documentserver

Mount data directory, configure JWT, and the service runs on your machine. This satisfies compliance for finance, healthcare, government — data, user info, audit logs never leave your infrastructure. SaaS cannot guarantee this; custom development is too costly; private deployment hits the sweet spot.

3.3 Collaboration

Collaboration is built-in, not a plugin.

Real-time editing : Multiple users see each other's cursors, selections, and online status. Two modes: Fast (real-time changes visible) and Strict (paragraph locking for focused writing).

Comments : Highlight text, add comments, @-mention collaborators. Comments and tracked changes coexist, ideal for review workflows.

Version history : View historical versions, diff, and rollback. Essential for audit trails in contracts, reports, approval drafts.

3.4 White-Labeling

Developer edition allows replacing the editor's logo, dark-mode logo, logo link URL, about-page company name/address/email, and theme colors via editorConfig.customization. The customer sees your brand, not "Powered by OnlyOffice." Brand consistency is part of the product experience for SaaS vendors; a third-party logo erodes trust. White-labeling makes OnlyOffice an invisible engine inside your product.

Note: OnlyOffice supports offline AI but requires separate local model deployment and configuration — another engineering effort.

Practical Demo: Spring Boot Integration

Four steps: Docker deploy, backend config generation, frontend editor load, handle save callback. Example project onlyoffice-springboot uses Spring Boot 3.4.5, Java 17, and JDK's HmacSHA256 for JWT (no extra framework).

Step 1: Docker Deploy with JWT

docker run -i -t -d -p 8080:80 
  -e JWT_ENABLED=true 
  -e JWT_SECRET=susantest123456 
  -v /data/onlyoffice/data:/var/www/onlyoffice/Data 
  onlyoffice/documentserver

Record JWT_SECRET; backend uses it for config signing and callback verification. Weak or missing secret exposes the document service.

Verify service readiness: docker ps to get container ID.

Inside container:

docker exec <id> curl -s http://127.0.0.1:8000/info/info.json | grep buildVersion

returns e.g. "buildVersion":"10.0.0".

Browser: http://<server-ip>:8080/welcome/ shows welcome page.

Check JWT status: docker exec <id> documentserver-jwt-status.sh.

Application config ( application.yml):

server:
  port: ${SERVER_PORT:8081}
  address: 0.0.0.0
onlyoffice:
  docs-url: ${ONLYOFFICE_DOCS_URL:http://localhost:8080}
  public-app-url: ${APP_PUBLIC_URL:https://your-app.example.com}
  jwt-secret: ${ONLYOFFICE_JWT_SECRET:}
  storage:
    directory: ${DOCUMENT_STORAGE_DIR:./data/documents}
docs-url

is where the browser loads api.js; public-app-url is where OnlyOffice server downloads files and sends callbacks. During local development, public-app-url cannot be localhost because the remote document server cannot reach your machine.

JWT Service Core

JwtService

signs config and download URLs with HS256, verifies callbacks. Key points:

Uses MessageDigest.isEqual for constant-time signature comparison.

Config token and download token are separate. Download token carries fileId and purpose: "document-download" so permissions don't mix.

@Service
public class JwtService {
  private static final Base64.Encoder BASE64_URL_ENCODER = Base64.getUrlEncoder().withoutPadding();
  private static final Base64.Decoder BASE64_URL_DECODER = Base64.getUrlDecoder();
  private final ObjectMapper objectMapper;
  private final OnlyOfficeProperties properties;
  
  public String sign(Map<String, Object> claims) {
    if (!properties.jwtEnabled()) throw new IllegalStateException("onlyoffice.jwt-secret not configured");
    Map<String, Object> payload = new LinkedHashMap<>(claims);
    long now = Instant.now().getEpochSecond();
    payload.putIfAbsent("iat", now);
    payload.putIfAbsent("exp", now + 3600);
    String header = encodeJson(Map.of("alg", "HS256", "typ", "JWT"));
    String body = encodeJson(payload);
    String signingInput = header + "." + body;
    return signingInput + "." + BASE64_URL_ENCODER.encodeToString(hmac(signingInput));
  }
  
  public Map<String, Object> verify(String token) {
    if (!properties.jwtEnabled()) return Map.of();
    if (token == null || token.isBlank()) throw new IllegalArgumentException("Missing JWT");
    String[] parts = token.split("\\.");
    if (parts.length != 3) throw new IllegalArgumentException("Invalid JWT format");
    String signingInput = parts[0] + "." + parts[1];
    byte[] expected = hmac(signingInput);
    byte[] actual = BASE64_URL_DECODER.decode(parts[2]);
    if (!MessageDigest.isEqual(expected, actual)) throw new IllegalArgumentException("Invalid JWT signature");
    Map<String, Object> claims = objectMapper.readValue(BASE64_URL_DECODER.decode(parts[1]), MAP_TYPE);
    Number expiresAt = (Number) claims.get("exp");
    if (expiresAt != null && expiresAt.longValue() < Instant.now().getEpochSecond()) throw new IllegalArgumentException("JWT expired");
    return claims;
  }
  
  private String encodeJson(Map<String, Object> value) throws Exception {
    return BASE64_URL_ENCODER.encodeToString(objectMapper.writeValueAsBytes(value));
  }
  
  private byte[] hmac(String input) throws GeneralSecurityException {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(properties.jwtSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    return mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
  }
}

Step 2: Backend Generates Config

Two critical details: document.key generation and file access. document.key = file ID + "_" + version. Increment version on successful save; next open gets a new key. Never use filename or timestamp.

Config generation endpoint:

@GetMapping("/config/{fileId}")
public Map<String, Object> getConfig(@PathVariable Long fileId) {
  StoredFile file = fileRepository.mustFind(fileId);
  String documentKey = file.getId() + "_" + file.getVersion();
  
  Map<String, Object> document = new LinkedHashMap<>();
  document.put("fileType", "docx");
  document.put("key", documentKey);
  document.put("title", file.getOriginalName());
  // This URL is fetched by OnlyOffice server, not browser
  document.put("url", "https://your-app.com/api/files/" + fileId + "/download");
  
  Map<String, Object> editorConfig = new LinkedHashMap<>();
  editorConfig.put("callbackUrl", "https://your-app.com/api/office/callback/" + fileId);
  editorConfig.put("lang", "zh-CN");
  editorConfig.put("user", Map.of("id", currentUserId(), "name", currentUserName()));
  
  Map<String, Object> config = new LinkedHashMap<>();
  config.put("document", document);
  config.put("editorConfig", editorConfig);
  config.put("token", jwtSigner.sign(config));
  return config;
}

Order matters: fill document and editorConfig completely, then sign the whole config. Signature must match what frontend receives.

File access: the url is requested by OnlyOffice server, not the browser. If files are in an intranet, ensure the document service container can reach that address. The example does not expose /api/files/{id}/download directly; instead it issues a 15-minute download token.

@Service
public class FileAccessService {
  private final JwtService jwtService;
  private final OnlyOfficeProperties properties;
  
  public String createDownloadUrl(String documentId) {
    String path = "/api/files/" + documentId + "/download";
    if (!properties.jwtEnabled()) return properties.publicUrl(path);
    Map<String, Object> claims = new LinkedHashMap<>();
    claims.put("fileId", documentId);
    claims.put("purpose", "document-download");
    claims.put("iat", Instant.now().getEpochSecond());
    claims.put("exp", Instant.now().plusSeconds(900).getEpochSecond());
    String token = jwtService.sign(claims);
    return UriComponentsBuilder.fromUriString(properties.publicUrl(path))
      .queryParam("access_token", token)
      .build(true).toUriString();
  }
  
  public void verifyDownload(String documentId, String token) {
    if (!properties.jwtEnabled()) return;
    Map<String, Object> claims = jwtService.verify(token);
    if (!documentId.equals(claims.get("fileId")) || !"document-download".equals(claims.get("purpose"))) {
      throw new IllegalArgumentException("Download token mismatch");
    }
  }
}

OnlyOffice requests e.g.

https://your-app.example.com/api/files/welcome-word/download?access_token=eyJ...

. Download endpoint verifies token, then streams file:

@GetMapping("/{id}/download")
public ResponseEntity<byte[]> download(@PathVariable String id,
    @RequestParam(name = "access_token", required = false) String accessToken) {
  fileAccessService.verifyDownload(id, accessToken);
  DocumentInfo document = storageService.get(id);
  byte[] content = storageService.read(id);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(mediaType(document.fileType()));
  headers.setContentDisposition(ContentDisposition.attachment()
    .filename(document.name(), StandardCharsets.UTF_8).build());
  headers.setCacheControl(CacheControl.noStore().cachePrivate().maxAge(Duration.ZERO));
  return ResponseEntity.ok().headers(headers).body(content);
}

Requests without access_token get 400. Browser knows file ID but cannot fetch content; only the short-lived token allows the document service to download.

Step 3: Frontend Loads Editor

Frontend fetches config, then dynamically loads api.js from the docsApiUrl returned in config.

<div id="office-editor" style="width:100%; height:100vh;"></div>
<script src="https://your-docserver/web-apps/apps/api/documents/api.js"></script>
<script>
const config = await fetch(`/api/office/config/${fileId}`).then(r => r.json());
await loadDocsApi(config.docsApiUrl);
config.events = {
  onAppReady: () => { loadingPanel.hidden = true; },
  onDocumentReady: () => { setStatus("saved", "Document loaded"); },
  onDocumentStateChange: event => {
    const changed = Boolean(event?.data);
    setStatus(changed ? "changed" : "idle", changed ? "Unsaved changes" : "Synced");
  },
  onError: event => {
    const code = event?.data?.errorCode ?? "unknown";
    const desc = event?.data?.errorDescription ?? "Unknown error";
    showError(`Error ${code}: ${desc}`);
  },
  onRequestClose: () => { window.location.href = "/"; }
};
new DocsAPI.DocEditor("office-editor", config);

function loadDocsApi(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = url;
    script.async = true;
    script.onload = resolve;
    script.onerror = () => reject(new Error("Failed to load ONLYOFFICE api.js"));
    document.head.appendChild(script);
  });
}
</script>

Note: onDocumentStateChange(false) only means editor-internal sync; real save result depends on server callback logs.

Step 4: Handle Save Callback

On status 2 (close, save needed) or 6 (forced save), download new file, update storage, increment version.

@PostMapping("/callback/{fileId}")
public Map<String, Integer> callback(@PathVariable Long fileId, @RequestBody Map<String, Object> body) {
  if (!jwtVerifier.verify(body)) return Map.of("error", 1);
  int status = (int) body.get("status");
  if (status == 2 || status == 6) {
    String downloadUrl = (String) body.get("url");
    byte[] newContent = restTemplate.getForObject(downloadUrl, byte[].class);
    fileStorage.update(fileId, newContent);
    fileRepository.incrementVersion(fileId); // refreshes key
  }
  return Map.of("error", 0);
}

Callback service ( OnlyOfficeCallbackService) adds: 10s connect timeout, 60s read timeout, 50MB max download size to avoid hung threads. Status codes to watch:

1 : Editing in progress — log only

2 : Closed, needs save — download & update version

4 : Closed, no changes — return success

6 : Forced save — download & update version

7 : Forced save error — log, do not overwrite

File write uses atomic replace: write to .tmp, then Files.move(..., REPLACE_EXISTING, ATOMIC_MOVE). withContent increments version:

public DocumentInfo withContent(long newSize) {
  return new DocumentInfo(id, name, fileType, version + 1, newSize, Instant.now());
}

Next open uses id + "_" + version as new document.key, avoiding stale cache.

Common Pitfalls

Key not updated → collaboration chaos (users see cached old version).

Callback doesn't save → user thinks content lost.

Callback returns non-zero or times out → OnlyOffice treats save as failed; next open shows pre-edit version.

JWT mismatch → editor fails to load with "document security token format error".

Version Selection Cheat Sheet

Small team, testing → Community. Key constraint: AGPL v3 viral; concurrency limit 20 (removed since v9.4).

Enterprise internal, keep brand → Enterprise. Key constraint: ≥50 concurrent; annual or perpetual license.

SaaS, need white-label → Developer. Key constraint: White-label; annual only.

Per-customer deployment → Depends on brand need. White-label → Developer; keep brand → Enterprise.

Conclusion

The three initial blockers — SaaS data egress, per-seat SDK cost, custom dev overhead — are resolved by turning "document editing" from a service into a self-hosted component. Data stays on your servers, capability embeds via API, licensing fits budget. Trade-offs: Community has AGPL and concurrency limits; white-label only in Developer; offline AI requires extra model deployment. But in the "private, embeddable, cost-controlled" coordinate system, OnlyOffice unblocks the dead-end road.

Selection boils down to two questions: must data stay in-house? must the brand be yours? Answers pick Community, Enterprise, or Developer. The rest is a Docker command and a config.

Links

Online trial: https://www.onlyoffice.com/zh/signup

Local deployment: https://www.onlyoffice.com/zh/download

Open source: https://github.com/ONLYOFFICE/DocumentServer

Enterprise edition: https://www.onlyoffice.com/zh/docs-enterprise

Developer edition: https://www.onlyoffice.com/zh/for-developers

Pricing & comparison: https://www.onlyoffice.com/zh/pricing

Help center: https://helpcenter.onlyoffice.com/zh/

API docs: https://api.onlyoffice.com/zh-CN/

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DockerSpring BootJWTCollaborationAPI IntegrationOnlyOfficeSelf-HostedDocument Editing
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.