This library is intended as a simple common interface for javascript applications to resolve DID documents from Decentralized Identifiers (DIDs).
This is intended to support the proposed Decentralized Identifiers spec from the W3C Credentials Community Group.
The library does not implement any specific DID method, but allows DID method implementors to release npm packages that applications can add.
The VerificationRelationship runtime constants represent the verification relationships defined by DID Core:
import { VerificationRelationship, type DIDDocument } from 'did-resolver'
const document: DIDDocument = {
id: 'did:example:123',
[VerificationRelationship.authentication]: ['did:example:123#key-1'],
}The corresponding VerificationRelationship type also accepts the underlying string literals. The existing
KeyCapabilitySection type remains available as a backwards-compatible alias.
You are now required to preconfigure a resolver during instantiation. The Resolver constructor expects a registry of
methods mapped to a resolver function. For example:
{
ethr: resolve,
web: resolve
}Each method resolver should expose a function called getResolver which will return an object containing one of these
key/value pairs. Then you can flatten them into one object to pass into the Resolver constructor.
import { Resolver } from 'did-resolver'
import ethr from 'ethr-did-resolver'
import web from 'web-did-resolver'
//returns an object of { methodName: resolveFunction}
const ethrResolver = ethr.getResolver()
const webResolver = web.getResolver()
//If you are using multiple methods you need to flatten them into one object
const resolver = new Resolver({
...ethrResolver,
...webResolver,
})
//Alternatively, for one method:
const singleMethodResolver = new Resolver(ethrResolver)DID Method resolvers created before version 3.0.0 of this library can be used as legacy resolvers.
import { Resolver } from 'did-resolver'
import web from 'web-did-resolver'
import sov from 'sov-did-resolver'
//returns an object of { methodName: resolveFunction}
const webResolver = web.getResolver()
const sovResolver = sov.getResolver()
//If you are using multiple methods you need to flatten them into one object
const resolver = new Resolver({}, {
legacyResolvers: {
...webResolver,
...sovResolver,
}
})
//Alternatively, for one legacy method:
const singleMethodResolver = new Resolver({}, { legacyResolvers: webResolver })The resolver presents a simple resolve() function that returns an ES6 Promise of a DIDResolutionResult, containing
didResolutionMetadata, didDocument (which can be null on failure), and didDocumentMetadata.
resolver.resolve('did:ethr:0xF3beAC30C498D9E26865F34fCAa57dBB935b0D74/some/path#fragment=123').then(result => console.log(result.didDocument))
// You can also use ES7 async/await syntax
const { didDocument } = await resolver.resolve('did:ethr:0xF3beAC30C498D9E26865F34fCAa57dBB935b0D74/some/path#fragment=123')Resolving DID Documents can be expensive. It is in most cases best to cache DID documents. Caching is controlled via the cache option, which accepts a boolean value or a custom DIDCache function.
The built-in cache uses a Map and does not have an automatic TTL, so entries don't expire. This is fine in most web, mobile and serverless contexts. If you run a long-running process, consider using a custom cache with expiration.
Enable the built-in cache by passing cache: true to the constructor:
const resolver = new Resolver({
ethr,
web
}, {
cache: true
})To disable caching entirely, pass cache: false:
const resolver = new Resolver({
ethr,
web
}, {
cache: false
})When the built-in cache is enabled, you can bypass it for a call using cache: false in DIDResolutionOptions:
const result = await resolver.resolve('did:example:123', { cache: false })Passing cache: true per call does not enable a cache disabled at construction. Custom caches decide how to handle these options.
For advanced use cases, implement a custom DIDCache function. It receives the parsed DID, a resolve function, and optional resolution options. The following assumes a TTL cache named cache with get(key) and set(key, value, ttlMilliseconds) methods:
import type { DIDCache } from 'did-resolver'
const customCache: DIDCache = async (parsed, resolve, options) => {
// Respect per-call cache control
if (options?.cache === false) return await resolve()
const cached = cache.get(parsed.didUrl)
if (cached !== undefined) return cached
const doc = await resolve()
cache.set(parsed.didUrl, doc, 60000) // 60s TTL
return doc
}
const resolver = new Resolver({
ethr,
web
}, {
cache: customCache
})Each DID method will have its own methods for looking up an identifier on its respective blockchain or other decentralized storage mechanism.
To avoid misconfiguration, method implementers should export a getResolver() function which returns an object mapping
the method name to a resolve(did: string, parsed: ParsedDID, didResolver: Resolvable, options: DIDResolutionOptions)
function. e.g. { ethr: resolve }.
The resolve function should accept a did string, and an object of type ParsedDID. The minimal example below returns a synthetic document; replace its creation with your method's lookup.
import type { DIDResolutionOptions, DIDResolutionResult, ParsedDID, Resolvable } from 'did-resolver'
export function getResolver() {
async function resolve(
did: string,
parsed: ParsedDID,
didResolver: Resolvable,
options: DIDResolutionOptions
): Promise<DIDResolutionResult> {
// For did:mymethod:abcdefg/some/path#fragment=123, parsed.did is
// 'did:mymethod:abcdefg' and parsed.didUrl contains the entire input URL.
// To resolve another DID during lookup, use didResolver.resolve(otherDid).
return {
didResolutionMetadata: { contentType: 'application/did+ld+json' },
didDocument: { '@context': 'https://www.w3.org/ns/did/v1', id: did },
didDocumentMetadata: {},
}
}
return { mymethod: resolve }
}The MyMethod getResolver() result could then be passed into the Resolver constructor. Note that it should be
flattened if used with other methods as well.
import { Resolver } from 'did-resolver'
import * as MyMethod from 'mymethod-did-resolver'
const myResolver = MyMethod.getResolver()
const resolver = new Resolver(myResolver)If your method has special syntax constraints beyond the base DID Core v1.0 spec, you can attach a method-specific parser to your resolver. This allows stricter syntax validation without duplicate parsing work.
Architecture: Method-specific parsers receive a DID Core v1.0 compliant ParsedDID result from the global parser and only check method-specific syntax constraints. This ensures all DIDs pass DID Core v1.0 parsing first, then method-specific syntax rules. The parser is part of the resolver enhancement — both are exported together from getResolver().
import type { DIDResolutionOptions, DIDResolutionResult, ParsedDID, Resolvable } from 'did-resolver'
export function getResolver() {
async function resolve(
did: string,
parsed: ParsedDID,
didResolver: Resolvable,
options: DIDResolutionOptions
): Promise<DIDResolutionResult> {
// Replace this synthetic document with your method's lookup.
return {
didResolutionMetadata: { contentType: 'application/did+ld+json' },
didDocument: { '@context': 'https://www.w3.org/ns/did/v1', id: did },
didDocumentMetadata: {},
}
}
function parser(parsed: ParsedDID): (ParsedDID & { methodSpecificField: string }) | null {
// Receive DID Core v1.0 compliant ParsedDID from global parser
// Only add method-specific syntax constraints
// Example: enforce minimum id length for this method
if (parsed.id.length < 5) {
return null // Reject with invalidDid error
}
// Can refine/enrich the parsed result if needed
return {
...parsed,
methodSpecificField: 'value'
}
}
// Attach parser to resolver — this is required for the parser to be used
resolve.parser = parser
return { mymethod: resolve }
}Consumers register the resolver normally — the parser is part of it:
import { Resolver } from 'did-resolver'
import * as MyMethod from 'mymethod-did-resolver'
// For a single method
const resolver = new Resolver(MyMethod.getResolver())
// Alternatively, for multiple methods, flatten them together
import * as OtherMethod from 'other-did-resolver'
const multiMethodResolver = new Resolver({
...MyMethod.getResolver(),
...OtherMethod.getResolver(),
})Benefits:
- Method libraries control their own parse→resolve pipeline as a cohesive unit
- Parser is discovered automatically via the resolver's
.parserproperty - No duplicate parsing work
- All DIDs guaranteed to pass DID Core v1.0 parsing first
- Method parsers only implement method-specific syntax constraints
- Parsers can refine/enrich the parsed result if needed
- If parser returns
null, resolution fails withinvalidDiderror