Obsidian SDK Patterns
Overview
Six production patterns that prevent the most common Obsidian plugin bugs: lost
settings on upgrade, null-reference crashes on deleted files, memory leaks from
unregistered events, stale metadata, and UI jank from rapid file changes. Each
pattern is self-contained and copy-pasteable.
Prerequisites
- A working Obsidian plugin (see
obsidian-core-workflow-a)
- TypeScript strict mode enabled (
"strictNullChecks": true in tsconfig)
- Familiarity with
Plugin.onload() / onunload() lifecycle
Instructions
Step 1: Typed settings with versioned migration
Settings break when you add or rename fields between releases. Version the
settings object and migrate on load so existing users keep their data.
interface PluginSettingsV1 {
apiKey: string;
interval: number;
}
interface PluginSettingsV2 {
version: 2;
apiKey: string;
syncInterval: number;
excludedFolders: string[];
theme: "default" | "minimal";
}
type PluginSettings = PluginSettingsV2;
const DEFAULTS: PluginSettings = {
version: 2,
apiKey: "",
syncInterval: 300,
excludedFolders: [],
theme: "default",
};
export async function loadSettings(plugin: Plugin): Promise<PluginSettings> {
const raw = (await plugin.loadData()) as any;
if (!raw) return { ...DEFAULTS };
if (!raw.version || raw.version < 2) {
raw.version = 2;
if (raw.interval !== undefined) {
raw.syncInterval = raw.interval;
delete raw.interval;
}
raw.excludedFolders = raw.excludedFolders ?? [];
raw.theme = raw.theme ?? "default";
await plugin.saveData(raw);
}
return { ...DEFAULTS, ...raw };
}
Why: Object.assign({}, DEFAULTS, raw) handles new fields added in patch
releases. The explicit migration block handles renames and type changes between
major versions.
Step 2: Safe vault operations (check-before-act)
The Vault API throws if you create a file that exists or read one that was
deleted between your check and your call. Wrap every operation.
import { App, TFile, TFolder, TAbstractFile, normalizePath } from "obsidian";
export class VaultHelper {
constructor(private app: App) {}
async safeRead(path: string): Promise<string | null> {
const file = this.app.vault.getAbstractFileByPath(normalizePath(path));
if (!(file instanceof TFile)) return null;
return this.app.vault.read(file);
}
async safeWrite(path: string, content: string): Promise<TFile> {
const normalized = normalizePath(path);
.(normalized);
existing = ...(normalized);
(existing ) {
...(existing, content);
existing;
}
...(normalized, content);
}
(: , : ): <> {
normalized = (path);
existing = ...(normalized);
(existing ) {
current = ...(existing);
...(existing, current + content);
} {
.(normalized);
...(normalized, content);
}
}
(: , useTrash = ): <> {
file = ...((path));
(!(file )) ;
(useTrash) {
...(file, );
} {
...(file);
}
;
}
(: ): <> {
parts = filePath.();
parts.();
current = ;
( part parts) {
current = current ? : part;
existing = ...(current);
(!existing) {
...(current);
}
}
}
}
Step 3: Event management with automatic cleanup
Every this.registerEvent(...) call in onload() is automatically cleaned up
when the plugin unloads. Never use raw addEventListener or app.vault.on()
without registering -- those leak.
export default class MyPlugin extends Plugin {
async onload() {
this.registerEvent(
this.app.vault.on("create", (file) => {
if (file instanceof TFile) this.onFileCreated(file);
})
);
this.registerEvent(
this.app.vault.on("delete", (file) => {
if (file instanceof TFile) this.onFileDeleted(file);
})
);
this.registerEvent(
this.app.vault.on("rename", (file, oldPath) => {
if (file instanceof TFile) this.(file, oldPath);
})
);
.(
...(, {
.(leaf);
})
);
.(
...(, {
.();
})
);
.(
.( .(), )
);
.(, , {
(evt. === ) .();
});
}
}
Anti-pattern to avoid:
this.app.vault.on("modify", handler);
document.addEventListener("click", handler);
this.registerEvent(this.app.vault.on("modify", handler));
this.registerDomEvent(document, "click", handler);
Step 4: Workspace layout manipulation
Open files in specific panes, split views, and restore layout state.
import { MarkdownView, WorkspaceLeaf } from "obsidian";
export class WorkspaceHelper {
constructor(private app: App) {}
async openInNewTab(path: string): Promise<void> {
const file = this.app.vault.getAbstractFileByPath(path);
if (!(file instanceof TFile)) return;
const leaf = this.app.workspace.getLeaf("tab");
await leaf.openFile(file);
}
async openInSplit(path: string): Promise<void> {
const file = this.app.vault.getAbstractFileByPath(path);
if (!(file instanceof )) ;
leaf = ...(, );
leaf.(file);
}
(): | {
view = ...();
view?. ?? ;
}
(: ): {
...( {
(leaf. && leaf..) {
(leaf.., leaf);
}
});
}
(): {
leaf = ...();
(leaf) {
pinned = (leaf ).;
(leaf ).(!pinned);
}
}
}
Step 5: Metadata cache for fast queries
metadataCache is Obsidian's pre-parsed index of all vault files. It avoids
reading file content for frontmatter, tags, links, and headings.
import { App, TFile, CachedMetadata } from "obsidian";
export class MetadataHelper {
constructor(private app: App) {}
getCache(file: TFile): CachedMetadata | null {
return this.app.metadataCache.getFileCache(file);
}
getFrontmatterValue(file: TFile, key: string): any | undefined {
const cache = this.getCache(file);
return cache?.frontmatter?.[key];
}
filesWithTag(tag: string): TFile[] {
const normalized = tag.startsWith("#") ? tag : `#${tag}`;
return this...().( {
cache = .(file);
bodyTags = cache?.?.( t.) ?? [];
fmTags = (cache?.?. ?? []).(
t.() ? t :
);
[...bodyTags, ...fmTags].(normalized);
});
}
(: ): [] {
cache = .(file);
links = cache?.?.( l.) ?? [];
embeds = cache?.?.( e.) ?? [];
[... ([...links, ...embeds])];
}
(: ): [] {
resolved = ...;
: [] = [];
( [sourcePath, targets] .(resolved)) {
(file. targets) {
source = ...(sourcePath);
(source ) results.(source);
}
}
results;
}
(: ): {
(...) {
();
} {
...(, callback);
}
}
(
: ,
: ,
:
): {
plugin.(
...(, {
(file. === filePath) (cache);
})
);
}
}
Step 6: Debounced file modification handlers
Plugins that react to file changes (auto-save, indexing, sync) fire too often
without debouncing. Obsidian's vault modify event fires on every keystroke
when live preview is active.
import { Plugin, TFile, debounce } from "obsidian";
export default class IndexerPlugin extends Plugin {
private processFile = debounce(
async (file: TFile) => {
console.log(`[Indexer] Processing ${file.path}`);
const content = await this.app.vault.read(file);
await this.updateIndex(file, content);
},
2000,
true
);
async onload() {
this.registerEvent(
this.app.vault.on("modify", (file) => {
if (file instanceof TFile && file.extension === "md") {
.(file);
}
})
);
}
(: , : ): <> {
}
}
For per-file debouncing (different timers for different files):
private fileTimers = new Map<string, ReturnType<typeof setTimeout>>();
private debouncedProcess(file: TFile, delayMs = 2000): void {
const existing = this.fileTimers.get(file.path);
if (existing) clearTimeout(existing);
this.fileTimers.set(
file.path,
setTimeout(async () => {
this.fileTimers.delete(file.path);
const content = await this.app.vault.read(file);
await this.updateIndex(file, content);
}, delayMs)
);
}
onunload() {
for (const timer of this.fileTimers.values()) {
clearTimeout(timer);
}
this..();
}
Output
After applying these patterns:
- Settings survive across plugin updates with automatic migration
- File operations never crash on missing files or duplicate paths
- All events auto-clean on plugin unload (zero memory leaks)
- Workspace manipulation opens files in tabs, splits, or sidebar
- Metadata cache provides instant tag/link/frontmatter queries without reading files
- File modification handlers are debounced to prevent UI jank and redundant work
Error Handling
| Error | Cause | Fix |
|---|
| Settings lost after update | No version field / no migration | Add version to settings interface, migrate in loadSettings |
null file reference | File deleted between check and use | Always re-fetch with getAbstractFileByPath immediately before use |
| Memory leak warning | Events registered without registerEvent | Wrap every .on() with this.registerEvent() |
| Stale metadata | Cache not yet updated after vault.modify | Listen to metadataCache.on('changed') instead of reading immediately |
| Plugin slows Obsidian | Processing every keystroke | Debounce modify handlers (2s+ delay) |
createFolder throws | Folder already exists | Check getAbstractFileByPath first |
normalizePath undefined | Forgot import | Import from "obsidian" |
Examples
Complete plugin using all patterns together:
import { Plugin, TFile, debounce, normalizePath } from "obsidian";
import { loadSettings, PluginSettings } from "./settings";
import { VaultHelper } from "./vault-helpers";
import { MetadataHelper } from "./metadata-helpers";
export default class MyPlugin extends Plugin {
settings: PluginSettings;
vault: VaultHelper;
meta: MetadataHelper;
async onload() {
this.settings = await loadSettings(this);
this.vault = new VaultHelper(this.app);
this.meta = new MetadataHelper(this.app);
const reindex = debounce(
.(file), ,
);
.(
...(, {
(f ) (f);
})
);
}
() {
content = ..(file.);
(!content) ;
tags = ..();
}
}
Resources
Next Steps
Debug and test: obsidian-local-dev-loop. Common errors: obsidian-common-errors. Release: obsidian-prod-checklist.