Getting started
@evanion/urn 2.1.0 and its patch releases up to 2.1.1, the version on npm. Values on this page were produced by running the source at f9b1d93, a later commit than the 2.1.0 tag, and are not re-executed.
When you need to identify resources across different systems—like distinguishing a game from an order—standard strings aren’t enough. You need a way to ensure that an identifier is not just a string, but a meaningful, valid reference to a specific kind of resource.
In this guide, you will create a GameURN class that can mint valid identifiers like urn:game:brass-birmingham and automatically refuse malformed ones.
Prerequisites
To get started with @evanion/urn, you will need:
- Node 20 or newer.
- An ESM project: If you’re starting from scratch, run
npm init -yand thennpm pkg set type=module. (Note: CommonJS projects require Node 20.19 or 22.12+ to load ES modules viarequire()).
The package is lightweight with no runtime or peer dependencies and ships its own types.
Install @evanion/urn
Run the command for your preferred package manager:
npm install @evanion/urnDefine your namespace
The core of the library is the namespace class. Instead of passing the namespace identifier (NID) as a string every time you call a function, you define a class that represents that namespace. This provides a clean way to handle different kinds of resources: GameURN.stringify needs no NID argument.
For a game shop, we’ll create a GameURN class that extends the base URN class and sets the nid to 'game'. Save this as game-urn.ts:
import { , } from '@evanion/urn';
class extends {
static override readonly = 'game';
}
const = .('brass-birmingham');
; // -> 'urn:game:brass-birmingham'
let = '';
try {
.('brass birmingham');
} catch () {
if ( instanceof ) = .;
}
; // -> "NSS contains invalid character ' ' in 'brass birmingham'"The stringify method uses the nid and the provided slug to create the full URN. Before joining them, it validates the slug against the URN grammar. For example, a space is invalid in a Namespace Specific String (NSS), so the second call in the example throws an InvalidError.
Run your code
The // -> comments in game-urn.ts show the expected output. To see it in your terminal, add console.log(id, refused); to the end of the file.
If you are using Node 22.18 or 23.6+, you can run the file directly:
node game-urn.tsOn older versions of Node, use npx tsx game-urn.ts. You should see:
urn:game:brass-birmingham NSS contains invalid character ' ' in 'brass birmingham'.
Next steps: Handling multiple namespaces
You’ve now seen how to mint a URN and validate a slug. But real applications often deal with many different kinds of identifiers at once.
In URNs from several namespaces, we’ll look at how to handle both game URNs and order URNs within a single list.