Routes and access
A route connects a URL path and an HTTP method to a method of your class. You declare it with
#[Core\Route]. Every route also needs #[Core\Access], which says who may use it. The compiler
collects all routes of the program into one table. Core\Router reads that table.
Core\Route and Core\Access
#[Core\Route] on a method gives it a path and an HTTP method. #[Core\Access] says who may use it. A route needs both.
A path has fixed segments and captures. {id} matches one segment, {id?} one or none, and {path...} all remaining segments. Each capture goes to the parameter with the same name, converted to its type. A parameter with #[Core\Query] gets its value from the query string. A bad query value is a 400, and the route method does not run.
Core\Router::url builds a link to the route of a method, such as Shop::show. Your entry file calls Core\Router::dispatch, which calls the method of the route that matches.
A Core\Time\Date, TimeOfDay or Instant can be a capture or a query value. A DateTime can only be a query value. Its zone name, such as Europe/Vienna, has a /, and in a path a / would split the value.
The examples below show links, captures, query values that may be missing, bool and time values, and a missing #[Core\Access].
The examples below run with this configuration file.
# `Core\Router::urlAbsolute` puts this origin in front of a path.[[app]]root = "."origin = "https://example.test"Declare a route and build a link
<?nvs// Shows how to declare a route and build a link to it. `#[Core\Route]` gives a// method a path, and `#[Core\Access]` says who may reach it. Every route needs// both. `Core\Router::url` builds the link to the route of a method.
class Users{ #[Core\Route(path: '/users', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function index(): string { return 'all users'; }
// `{id}` is a capture. It fills one segment of the path, and the parameter // `$id` says the value there is a whole number. #[Core\Route(path: '/users/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function show(uint $id): string { return 'user ' . $id; }}
// `Users::index` without brackets is a method reference. It names the method// and does not call it. This prints `/users` and then `/users/7`.echo Core\Router::url(Users::index), "\n";echo Core\Router::url(Users::show, ['id' => 7]), "\n";
// A route method is an ordinary method. You can call it yourself.echo (new Users())->show(7), "\n";/users/users/7user 7Captures that convert and a query parameter
<?nvs// Shows the three kinds of capture, and a parameter that comes from the query// string. The type you declare for a parameter is what its part of the path// converts to.
class Docs{ enum Lang { En, De }
// `{page?}` matches one segment or none, so `$page` needs a default value. // `#[Core\Query]` fills `$q` from the query string instead of the path. #[Core\Route(path: '/{lang}/docs/{page?}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function page(Lang $lang, uint $page = 1, #[Core\Query] string $q = ''): string { return 'docs'; }
// `{path...}` matches everything that is left, the `/` characters included. #[Core\Route(path: '/files/{path...}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function file(string $path): string { return 'file'; }}
// A value you leave out drops its segment. This prints `/De/docs`.echo Core\Router::url(Docs::page, ['lang' => Docs::Lang::De]), "\n";
// A key that is not a capture becomes the query string, and the space in `a b`// is encoded. This prints `/En/docs/3?q=a+b`.echo Core\Router::url(Docs::page, ['lang' => Docs::Lang::En, 'page' => 3, 'q' => 'a b']), "\n";
// This prints `/files/a/b%20c.txt`.echo Core\Router::url(Docs::file, ['path' => 'a/b c.txt']), "\n";/De/docs/En/docs/3?q=a+b/files/a/b%20c.txtLinks for a product list
<?nvs// A product list with paging, as a web page needs it. Every link comes from// the route table, so a path you change in one place changes everywhere.
enum Role { Customer, Staff }
class Products{ #[Core\Route(path: '/products', method: Core\Http\Method::Get)] #[Core\Access(allow: Role::Customer)] public function list(#[Core\Query] uint $page = 1, #[Core\Query] string $sort = 'name'): string { return 'products'; }
#[Core\Route(path: '/products/{sku}', method: Core\Http\Method::Get)] #[Core\Access(allow: Role::Customer)] public function show(string $sku): string { return $sku; }
// `allow:` takes any constant, and `Role::Staff` is this program's own. // Novis records the decision and does not read what it means. #[Core\Route(path: '/products/{sku}', method: Core\Http\Method::Delete)] #[Core\Access(allow: Role::Staff)] public function delete(string $sku): string { return $sku; }}
uint $page = 2;
// The link to the next page of the list, sorted by price.echo Core\Router::url(Products::list, ['page' => $page + 1, 'sort' => 'price']), "\n";
// The link to one product, and the link that deletes it. Both paths are the// same, because the two routes differ in their HTTP method.echo Core\Router::url(Products::show, ['sku' => 'cup-01']), "\n";echo Core\Router::url(Products::delete, ['sku' => 'cup-01']), "\n";/products?page=3&sort=price/products/cup-01/products/cup-01Routes in another file
<?nvs// Shows that the route table also has the routes of every file that `autoload`// can reach. The class `App\Users` is in the file `routes/Users.nvs`.
autoload 'App' from './routes';
// This prints `/users/7` and then `/users`.echo Core\Router::url(App\Users::show, ['id' => 7]), "\n";echo Core\Router::url(App\Users::create), "\n";
// `urlAbsolute` puts the `origin` setting from `nvs.toml` in front of the path.// This prints `https://example.test/users/7`.echo Core\Router::urlAbsolute(App\Users::show, ['id' => 7]), "\n";/users/7/usershttps://example.test/users/7Call the route method yourself
<?nvs// Shows how a program finds the route for a request and calls its method// itself. `Core\Router::match` finds the route for an HTTP method and a path,// so this example runs without a server.
class Users{ #[Core\Route(path: '/users/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function show(uint $id): string { return 'user ' . $id; }
#[Core\Route(path: '/users', method: Core\Http\Method::Post)] #[Core\Access(allow: Core\Audience::Public)] public function create(): string { return 'created'; }}
class App{ public static function answer(Core\Http\Method $method, string $path): string { var $match = Core\Router::match($method, $path);
// `match` returns `null` when no route has this method and path. An empty // array from `methodsFor` means the path does not exist. if ($match == null) { return Core\Router::methodsFor($path) == [] ? '404' : '405'; }
// The server does not check the `allow:` value. Your program checks it. if ($match->accessAs<Core\Audience>() != Core\Audience::Public) { return '403'; }
// `is` checks whether the match is the route of the method you name. var $users = new Users(); if ($match->is(Users::show)) { return $users->show($match->parameter('id') as uint); } if ($match->is(Users::create)) { return $users->create(); } return '404'; }}
// This prints `user 7`, `created`, `405` and `404`.echo App::answer(Core\Http\Method::Get, '/users/7'), "\n";echo App::answer(Core\Http\Method::Post, '/users'), "\n";echo App::answer(Core\Http\Method::Delete, '/users'), "\n";echo App::answer(Core\Http\Method::Get, '/nothing'), "\n";user 7created405404A route needs an access decision
<?nvs// Shows that every route needs `#[Core\Access]`. This route has none, so the// program does not compile.// proof: compile-error
class Users{ #[Core\Route(path: '/users', method: Core\Http\Method::Get)] public function index(): string { return 'users'; }}error[E0762]: the route `Users::index` declares no access decision --> 06-a-route-needs-an-access-decision.nvs:8:7 |8 | #[Core\Route(path: '/users', method: Core\Http\Method::Get)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this route has no sibling `#[Access]` = help: a route without `#[Access]` has no default access. If everyone may call this route, write `#[Access(allow: Core\Audience::Public)]` on the method
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A query parameter and a bad value
<?nvs// Shows typed query values, the `400` for a bad value, and a route that reads a bad value as page 1.use Core\Http\Method;
class Shop{ // `#[Core\Query]` takes `$sort` and `$page` from the query string. // `$sort` has no default value, so every request must send it. #[Core\Route(path: '/products', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function products(#[Core\Query] 'name'|'price' $sort, #[Core\Query] uint $page = 1): void { echo 'page ', $page, ' sorted by ', $sort; }
// `$page` is a `string`, so every value is allowed. // `as ?uint` gives `null` for text that is not a whole number, and `?? 1` then gives `1`. #[Core\Route(path: '/search', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function search(#[Core\Query] string $page = ''): void { uint $number = ($page as ?uint) ?? 1; echo 'search page ', $number; }}
class Gate implements Core\Router\Gate{ public function allows(Core\Router\Match $route): bool { return true; }
// When a query value does not convert to its type, the route method does not run. // The server calls `refused` instead, with the reason `Refusal::BadCapture`. public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void { echo 'The address is not valid.'; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // `page` is missing, so `$page` is `1`. This prints `200`. var $first = Core\Test::request(Method::Get, '/products?sort=name'); echo $first->status(), ' ', $first->body(), "\n";
// This prints `200` and page 3. var $third = Core\Test::request(Method::Get, '/products?sort=price&page=3'); echo $third->status(), ' ', $third->body(), "\n";
// `three` is not a whole number. This prints `400`. var $word = Core\Test::request(Method::Get, '/products?sort=name&page=three'); echo $word->status(), ' ', $word->body(), "\n";
// `sort` is missing, and it has no default value. This prints `400`. var $missing = Core\Test::request(Method::Get, '/products?page=2'); echo $missing->status(), ' ', $missing->body(), "\n";
// `abc` is not a whole number, so `/search` shows page 1. This prints `200`. var $fallback = Core\Test::request(Method::Get, '/search?page=abc'); echo $fallback->status(), ' ', $fallback->body(), "\n";
// This prints `200` and page 5. var $fifth = Core\Test::request(Method::Get, '/search?page=5'); echo $fifth->status(), ' ', $fifth->body(), "\n";}200 page 1 sorted by name200 page 3 sorted by price400 The address is not valid.400 The address is not valid.200 search page 1200 search page 5A query value that may be missing
<?nvs// Shows query values that a request may leave out, and how to tell when a value is missing.use Core\Http\Method;
// `Tag::parse` throws an error for empty text and for text that is not in lower case.final class Tag implements Parses{ public function constructor(public tainted string $text) {}
public static function parse(tainted string $s): static { if ($s == '' || $s != Core\Str::lower($s)) { throw new ParseError('a tag is written in lower case'); } return new static($s); }
public function format(): tainted string { return $this->text; }}
class Blog{ // Each key may be missing, and then its value is `null`. A `page` that is there must be // a whole number, and `Tag::parse` reads a `tag` that is there. #[Core\Route(path: '/posts', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function posts(#[Core\Query] ?uint $page = null, #[Core\Query] ?Tag $tag = null): void { echo $page == null ? 'every page' : 'page ' . $page; echo ', ', $tag == null ? 'every tag' : 'tag ' . $tag->text; }}
class Gate implements Core\Router\Gate{ public function allows(Core\Router\Match $route): bool { return true; }
// When a query value does not convert to its type, the route method does not run. // The server calls `refused` instead, with the reason `Refusal::BadCapture`. public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void { echo 'The address is not valid.'; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // Both keys are missing, so both values are `null`. This prints `200`. var $none = Core\Test::request(Method::Get, '/posts'); echo $none->status(), ' ', $none->body(), "\n";
// This prints `200`, page 2 and the tag `news`. var $both = Core\Test::request(Method::Get, '/posts?page=2&tag=news'); echo $both->status(), ' ', $both->body(), "\n";
// `two` is not a whole number. This prints `400`. var $word = Core\Test::request(Method::Get, '/posts?page=two'); echo $word->status(), ' ', $word->body(), "\n";
// `News` is not in lower case, so `Tag::parse` throws an error. This prints `400`. var $upper = Core\Test::request(Method::Get, '/posts?tag=News'); echo $upper->status(), ' ', $upper->body(), "\n";
// `Core\Router::url` leaves out a key whose value is `null`. This prints `/posts?tag=news`. ?uint $page = null; echo Core\Router::url(Blog::posts, ['page' => $page, 'tag' => new Tag('news')]), "\n";}200 every page, every tag200 page 2, tag news400 The address is not valid.400 The address is not valid./posts?tag=newsA yes or no query value
<?nvs// Shows a `bool` query value, which a request writes as `1` for true and `0` for false.use Core\Http\Method;
class Feed{ // `$full` is `false` when the key is missing. // A checkbox in a form needs `value="1"`. Without it, a browser sends `on`, and that is a `400`. #[Core\Route(path: '/feed', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function feed(#[Core\Query] bool $full = false): void { echo $full ? 'the full feed' : 'the short feed'; }}
class Gate implements Core\Router\Gate{ public function allows(Core\Router\Match $route): bool { return true; }
// When a query value does not convert to its type, the route method does not run. // The server calls `refused` instead, with the reason `Refusal::BadCapture`. public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void { echo 'The address is not valid.'; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // `1` is `true`. This prints `200` and the full feed. var $yes = Core\Test::request(Method::Get, '/feed?full=1'); echo $yes->status(), ' ', $yes->body(), "\n";
// `0` is `false`. This prints `200` and the short feed. var $no = Core\Test::request(Method::Get, '/feed?full=0'); echo $no->status(), ' ', $no->body(), "\n";
// `on` is not `1` or `0`. This prints `400`. var $on = Core\Test::request(Method::Get, '/feed?full=on'); echo $on->status(), ' ', $on->body(), "\n";
// `Core\Router::url` writes `true` as `1`. This prints `/feed?full=1`. echo Core\Router::url(Feed::feed, ['full' => true]), "\n";}200 the full feed200 the short feed400 The address is not valid./feed?full=1A date in the path and a time in the query
<?nvs// Shows a date and a moment in the path, a date and time with its zone in the query, and their links.use Core\Http\Method;use Core\Time\Date;use Core\Time\DateTime;use Core\Time\Instant;
class Calendar{ // `{day}` is a `Date`, and `{since}` is an `Instant`. A `DateTime` can only be a query value. // Its zone name, such as `Europe/Vienna`, has a `/`, and in a path a `/` would split the value. #[Core\Route(path: '/days/{day}/since/{since}', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function day(Date $day, Instant $since, #[Core\Query] ?DateTime $meeting = null): void { echo 'day ', $day->toIso(), ', since ', $since->toIso(); echo ', meeting ', $meeting?->toIso() ?? 'none'; }}
class Gate implements Core\Router\Gate{ public function allows(Core\Router\Match $route): bool { return true; }
public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void { echo 'The address is not valid.'; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { var $day = Date::fromIso('2026-01-05'); var $since = Instant::fromIso('2026-01-05T08:30:00+01:00'); var $meeting = DateTime::fromIso('2026-01-05T14:00:00+01:00[Europe/Vienna]');
// The path has the ISO text of each value. An `Instant` is written in UTC. // This prints `/days/2026-01-05/since/2026-01-05T07:30:00Z`. echo Core\Router::url(Calendar::day, ['day' => $day, 'since' => $since]), "\n";
// In the query string, `:`, `+`, `/` and the brackets are percent-encoded. string $link = Core\Router::url(Calendar::day, ['day' => $day, 'since' => $since, 'meeting' => $meeting]); echo $link, "\n";
// The route reads the link it built. This prints `200` and the three values. var $answer = Core\Test::request(Method::Get, $link); echo $answer->status(), ' ', $answer->body(), "\n";
// February has no day 30, so no route matches. This prints `404`. var $bad = Core\Test::request(Method::Get, '/days/2026-02-30/since/2026-01-05T07:30:00Z'); echo $bad->status(), ' ', $bad->body(), "\n";
// A `DateTime` needs its zone in brackets. This prints `400`. var $noZone = Core\Test::request(Method::Get, '/days/2026-01-05/since/2026-01-05T07:30:00Z?meeting=2026-01-05T14:00:00'); echo $noZone->status(), ' ', $noZone->body(), "\n";}/days/2026-01-05/since/2026-01-05T07:30:00Z/days/2026-01-05/since/2026-01-05T07:30:00Z?meeting=2026-01-05T14%3A00%3A00%2B01%3A00%5BEurope%2FVienna%5D200 day 2026-01-05, since 2026-01-05T07:30:00Z, meeting 2026-01-05T14:00:00+01:00[Europe/Vienna]404 The address is not valid.400 The address is not valid.Details
Novis collects every route into one table at compile time. You write the method for Core\Router::url without brackets, such as Shop::show. An unknown method, a method with no route or a missing capture is a compile error. The server matches each request to a route before your program runs. A program can read the match with Core\Request::route().
A parameter written ?uint $page = null is optional. When the key is missing, the value is null. When the key is there, its value converts as a uint, and a bad value is a 400. This works for every type that a query parameter can have, such as a class that implements Parses.
A bool query value is 1 for true and 0 for false. Any other text, such as true or on, is a 400. A checkbox in a form sends on, so give it value="1".
A capture or a query value may be a Core\Time\Date, TimeOfDay or Instant. A #[Core\Query] value may also be a Core\Time\DateTime. Each is read from the text its toIso method writes, such as 2026-01-05, 08:30:00 or 2026-01-05T07:30:00Z. An Instant needs Z or an offset such as +01:00. A DateTime needs its zone in brackets, such as 2026-01-05T14:00:00+01:00[Europe/Vienna]. For a DateTime, the offset +01:00 may be left out. A DateTime path capture is E0752. The zone name has a /, which a path can only carry as %2F, and the server does not accept %2F in a path. Use an Instant in the path instead.
A time capture is read as it arrived, so 08%3A30 is not 08:30. A capture that does not convert is a 404, and a query value that does not convert is a 400. In a query string, a + that you type is read as a space, so that value is a 400. Write it as %2B.
Core\Router::url writes a time value as its ISO text. In the path the text is not encoded. In the query string, :, +, / and the brackets are percent-encoded, and the route reads that link.
A path must start with /, or it is E0750. A {name?} or {name...} capture that is not the last segment is E0750 too. A route with no method: is E0747, and a method: that is not a case of Core\Http\Method is E0401.
Two routes with the same path and the same HTTP method are E0748. This is true when they are in two classes, and when their captures only have different names, such as /users/{id} and /users/{key}. One method may have several #[Core\Route] lines, one for each HTTP method. They must all have the same path. Two different paths on one method are E0891.
A capture parameter may be a string, int, uint, decimal or an enum. It may also be a set of allowed values such as "en"|"de", or a class that implements Parses.
A capture with no parameter of the same name is E0751. A float parameter is E0752, and so is a {name...} parameter that is not a string. A {name?} parameter with no default value is E0753. A #[Core\Query] parameter takes the same types as a capture. It may also be ?T $x = null for any of those types T. A ?T with no default, or with a default that is not null, is E0752. A bool path capture does not compile, but a bool query value does. #[Core\Query] on a method with no route is E0765.
Core\Router::dispatch reads the query string key with the same name as the parameter. A parameter with a default value makes its key optional, and a missing key gives the default. These requests are a 400, and the route method does not run:
- a value that does not convert to the parameter's type, also for a
?T $x = nullparameter, - a
boolvalue that is not1or0, such astrue,on, an empty value or a key with no=, - a missing key for a parameter with no default value,
- a key that is sent twice,
- a key with brackets, such as
page[]=1.
For each 400, refused gets Core\Router\Refusal::BadCapture and the match. A path capture that does not convert is a 404, because then no route matches the request.
Sometimes a wrong link should still show a page. For this, declare the parameter as a string with a default, such as string $page = ''. Any valid UTF-8 text converts to a string, so the request is not a 400. Then convert the value in the route method, such as ($page as ?uint) ?? 1. A bad value gives 1. A typed parameter is the better choice in most cases, because it checks the value for you.
A route with no #[Core\Access] is E0762. #[Core\Access] on a method with no route is E0788. Two #[Core\Access] lines on one method are E0763, and one with no allow: is E0760. The allow: value must be an enum case or a class constant. A number is E0761. csrf: false on a method whose routes are all Head or Options is E0764. It is allowed on Get, because a WebSocket upgrade arrives as a Get.
The server checks the Origin header before it looks for a route. A POST, PUT, PATCH or DELETE from another origin gets Core\Router\Refusal::Csrf and the status 403. This is also true when no route has its path. So a request gets NotFound only when it comes from the same origin, has no Origin, or uses Get, Head or Options.
A fixed segment is tried before a capture, so /users/new matches the route /users/new and not /users/{id}. The order of the two routes in the code does not matter.
A fixed segment is compared exactly, so /U does not match /u. A path with an extra / at the end, such as /u/, does not match the route /u. An int capture matches -4, +4 and 04. It does not match a number too large for an int. A uint capture does not match a negative number. A decimal capture matches 1.50 and not x. A {name...} capture needs at least one segment, so /files does not match /files/{path...}.
An enum capture matches the name of a case exactly, such as De, and not de or 1. When every case of the enum has a written value, the capture matches that value instead. For enum Lang { En = 3, De = 7 }, /7 matches and /De does not.
A capture of a class that implements Parses matches any segment. The class's parse method runs inside Core\Router::match, before it returns. If parse throws an error, Core\Router::match throws the same error.
$match->parameter("id") returns uint|int|null|decimal|tainted string|Core\Uuid|Parses, so you convert it with as. A string capture gives a tainted string. A name that is not a capture gives null. Inside Core\Router::dispatch, the match also has each #[Core\Query] value under its parameter's name, so allows can read it. The match from Core\Request::route() has no query values. access() returns the full name of the allow: value, such as Role::Staff or Users::ADMIN. accessAs<Core\Audience>() on a route with allow: Role::Staff returns null.
Core\Router::url with a method that has no #[Core\Route] is E0754. A method the class does not have is E0309. A params array that leaves out a capture is E0755. A key that is neither a capture nor a #[Core\Query] parameter is E0759. A value outside a closed set, such as "fr" for "en"|"de", is E0772. These checks need the method reference and the array written directly in the code.
A method reference written in the call works for a static method and an instance method. The link does not call the method. You can also pass a method reference in a variable, such as an array<callable> for a menu. A static method goes in as Shop::products. An instance method goes in as $shop->order(...). A callable with no route throws a RuntimeError when the program runs. A params array in a variable that leaves out a capture throws a RuntimeError too.
The compiler checks the type of each value written in the params array. A value whose type the parameter cannot take is E1010, such as a Date for a uint capture. A string value always compiles. "x" for a uint capture gives the link /x, and that link does not match the route. A value of a class that implements Parses is written as the text its format method returns. Any other object throws a RuntimeError.
A capture value is encoded for one segment, so x/y?z# becomes x%2Fy%3Fz%23. An empty string gives an empty segment. A space is %20 in the path and + in the query string, and & in a query value is %26. A {name?} key that you leave out drops its segment, so the link is /u. A null value for it gives /u/, and the route matches that link too. A null value for a #[Core\Query] key leaves that key out of the query string.
Core\Router::urlAbsolute with no origin setting throws a RuntimeError. An origin that ends in / does not give two / characters in the link.
A few facts the examples do not show:
Core\Router::urlAbsoluteputs the origin in front, such ashttps://example.com. The origin is theoriginsetting under[[app]]innvs.toml.Post,Put,PatchandDeleterequests are checked for CSRF (a request sent from another site). AGetrequest that opens a WebSocket from another site is not allowed.csrf: falseturns off both checks for one method: the CSRF check, and the check of a WebSocket from another site. You write it in#[Core\Access], as in#[Core\Access(allow: Core\Audience::Public, csrf: false)]. On#[Core\Route], it does not compile.- Use
csrf: falseonly on a route that does not use the session cookie. A webhook that another server signs is one example. Without the check, another site can send a form with your visitor’s cookie. The webhook example shows such a route.
Handling a request
Section titled “Handling a request”nvs serve finds the route for each request before your program runs. Core\Router::dispatch
then calls the method of that route. You give dispatch a gate. A gate is an object of your own
class that implements Core\Router\Gate.
<?nvs// This program lets `Core\Router::dispatch` call the method of each route.use Core\Http\Method;use Core\Router\Refusal;
class Users{ #[Core\Route(path: '/users/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function show(uint $id): void { echo 'user ', $id; }}
// The gate checks each request before a route method runs, and it writes the error pages.class Gate implements Core\Router\Gate{ // The route method runs only when this returns `true`. public function allows(Core\Router\Match $route): bool { return $route->accessAs<Core\Audience>() == Core\Audience::Public; }
// No route method can run. `dispatch` has already set the status, such as 404 or 405. public function refused(Refusal $reason, ?Core\Router\Match $route): void { string $text = match ($reason) { Refusal::NotFound => 'no page has this address', Refusal::MethodNotAllowed => 'this address does not accept this method', default => 'this request is not allowed', }; echo $text; }
// A route method threw an error. The status is 500. public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'something went wrong'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // From the command line, this part sends three requests. It needs no server. var $found = Core\Test::request(Method::Get, '/users/7'); echo $found->status(), ' ', $found->body(), "\n"; var $wrongMethod = Core\Test::request(Method::Put, '/users/7'); echo $wrongMethod->status(), ' ', $wrongMethod->body(), "\n"; var $missing = Core\Test::request(Method::Get, '/nothing'); echo $missing->status(), ' ', $missing->body(), "\n";}user 7200 user 7405 this address does not accept this method404 no page has this addressfailedalso runs when the program uses too much memory or time. The status is500.- A
#[Core\Query]value that cannot be converted givesRefusal::BadCaptureand the status400. A missing required query key and a repeated one give the same. - A path capture such as
uint $idthat cannot be converted does not match the route, so the status is404. A capture of aParsesclass is different. When itsparsemethod throws an error, the result isRefusal::BadCaptureand the status400. #[Core\Query] ?int $page = nullis an optional query value. When the key is missing,$pageisnull.Core\Router::urlleaves out a key whose value isnull.- A
boolquery value is written1or0. Any other text gives the status400. A browser sendsonfor a checkbox, so writevalue="1"on it. A path capture cannot be abool. - A capture or a query value can be a
Core\Time\Date,TimeOfDayorInstant. A query value can also be aDateTime. Each is written as its ISO text, such as2026-03-09. A path segment that is not a valid date does not match the route, so the status is404. - A
DateTimeis a query value only. Its text has a time zone name, such asEurope/Vienna, and a/cannot be in a path segment. Core\Router::urlwrites a time value as its ISO text. It writes an object of aParsesclass as the text of itsformatmethod. A value whose type the parameter cannot take does not compile.dispatchconverts every capture and query value before it calls the gate’sallowsmethod. So$route->parameter('page')returns the query valuepagewith its type. Afinalclass’sparsecan load a stored record, andallowscan check that record.- A route method is
static, or its class has a constructor without parameters. - A route method can return a value, such as its page. When the gate implements
Core\Router\Responder,dispatchgives that value to the gate’srespondmethod. A plain gate does not use the value, andnvs checkgives a warning for it. - A request that the server stopped, for example in the CSRF check, never reaches a route method.
dispatchcallsrefusedfor it. - The server checks the
Originheader before it looks for a route. APOST,PUT,PATCHorDELETEfrom another site getsRefusal::Csrfand the status403. This is also true when no route has that path.
The reference page of Core\Router::dispatch has more examples.
When you call the route method yourself, Core\Router::match returns null for a path no route
has. Core\Router::methodsFor($path) returns the methods the path has. An empty array means 404,
and any other array means 405. The server does not check accessAs. Your program checks it
before it calls the method. Without dispatch, the CSRF check is the only check that runs for you.
Link to another module
Section titled “Link to another module”A module is a program with its own entry file on the same server. A program can link to a route of
another module. It declares the classes of the other modules with autoload links, as in
autoload links discover 'Framework' from '../../*/src';. Then
Core\Router::url(Index::show, ['id' => 3]) returns the URL of that route in the other module.
- A
useimport of such a class is allowed. Any other use of the class does not compile. - The class is not compiled into your program. Your program cannot call its methods.
- The compiler checks the link as it checks a local link. The method must exist and have a
#[Core\Route], and every capture needs a value. nvs.tomlsays where each module is served, such as under the path/shop. This place is called a mount. When the server starts, it adds the other module’s mount to the link.Core\Router::urlSignedcannot link to another module. Such a call does not compile.
The page Many modules on one server shows a complete setup.
A method that takes a route
Section titled “A method that takes a route”Your own method can take a route method and its values, as Core\Router::url does. Write
#[Core\Router\Target] on its callable parameter and #[Core\Router\Params] on its array
parameter. The compiler then checks each call that writes the route method directly, as it checks a
link.
Core\Router\Target and Core\Router\Params
#[Core\Router\Target] on a callable parameter says that the method takes a route method. #[Core\Router\Params] on an array parameter of the same method says that the array fills that route's path. Your own method then takes a route the way Core\Router::url does.
When a call writes the route method directly, such as Links::entry(Shop::show, ['id' => 3]), the compiler checks it like a link. The method needs a #[Core\Route]. The array needs a key for every capture, and each key must be a capture or a #[Core\Query] parameter. A value the capture cannot convert is an error too.
The call is an ordinary call. Your method gets the route method as a callable value. It can pass it to Core\Router::url, or call it. A route method in a variable is checked when the program runs.
A private route method can only be passed from inside its own class. To link to another module, call Core\Router::url directly.
The examples below show a method that builds a link, one that signs a link, and a menu built from route methods.
A wrapper that builds a link
<?nvs// Shows how your own method can take a route and its values, like `Core\Router::url` does.
class Shop{ #[Core\Route(path: '/shop/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public static function show(uint $id): string { return 'product ' . $id; }}
class Links{ // `$route` must be a route method, and `$params` fills its path. // The method passes both to `Core\Router::url` and returns the link. public static function url(#[Core\Router\Target] callable $route, #[Core\Router\Params] array<mixed> $params): string { return Core\Router::url($route, $params); }}
// The compiler checks this call like a call to `Core\Router::url`.// This prints `/shop/3`.echo Links::url(Shop::show, ['id' => 3]), "\n";/shop/3A wrapper that signs a link
<?nvs// Shows a method that signs a link, so the caller only gives the route and its values.
class Reports{ #[Core\Route(path: '/reports/{year}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public static function download(uint $year): string { return 'the report'; }}
class Links{ // This method makes the key and the expiry time itself. // The signed link works for one hour. public static function signed(#[Core\Router\Target] callable $route, #[Core\Router\Params] array<mixed> $params): string { secret bytes $key = Core\Crypto::generateKey(); array<secret bytes> $keys = [$key]; Core\Time\Instant $until = Core\Time::now()->plus(1h); return Core\Router::urlSigned($route, $params, { keys: $keys, until: $until }); }}
string $plain = Core\Router::url(Reports::download, ['year' => 2024]);string $signed = Links::signed(Reports::download, ['year' => 2024]);
// This prints `/reports/2024`.echo $plain, "\n";
// The signed link is the plain link with `?_sig=` and the signature at the end.// This prints `yes`.echo Core\Str::startsWith($signed, $plain . '?_sig=') ? 'yes' : 'no', "\n";/reports/2024yesA menu built from route methods
<?nvs// Shows how to build a menu from a list of route methods.
class Pages{ #[Core\Route(path: '/', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public static function home(): string { return 'home'; }
#[Core\Route(path: '/about', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public static function about(): string { return 'about'; }
#[Core\Route(path: '/contact', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public static function contact(): string { return 'contact'; }}
class Menu{ // These routes have no captures, so the method needs no `Params` parameter. public static function item(#[Core\Router\Target] callable $route, string $label): string { return '<a href="' . Core\Router::url($route) . '">' . $label . '</a>'; }}
// Each key is the text of a link, and each value is a route method.array<callable> $pages = ['Home' => Pages::home, 'About' => Pages::about, 'Contact' => Pages::contact];
// `$route` is a variable, so the route is found when the program runs.// This prints one link for each page. The first is `<a href="/">Home</a>`.foreach ($pages as string $label => callable $route) { echo Menu::item($route, $label), "\n";}<a href="/">Home</a><a href="/about">About</a><a href="/contact">Contact</a>Details
You write #[Core\Router\Target] and #[Core\Router\Params] on the parameters of a method or a constructor. On a method, a class, a property or a promoted constructor parameter, they are E0874.
A Target parameter has the type callable, a callable(...) type, or either one with ?. A Params parameter has the type array or array<...>, with or without ?. Any other type is E0899, and so is a variadic parameter.
A method has at most one Target and at most one Params. A second one is E1000. A Params needs a Target in the same method, or it is E1000 too. A Target alone is allowed, for a route with no captures. Neither attribute takes arguments.
These are the checks at a call that writes the route method directly:
- A method with no
#[Core\Route]isE0754. A method the class does not have isE0309. - An array that leaves out a capture is
E0755. - A key that is neither a capture nor a
#[Core\Query]parameter isE0759. - A written value that the capture cannot convert is
E0772, such as"x"for auint. A value outside a set of allowed values, such as"fr"for"en"|"de", isE0772too.
Each error names your method. A named argument, such as route: Shop::show, is checked in the same way. An array in a variable is not checked. When the call leaves out the Params argument, only the route is checked.
A route method in a variable is not checked while the program compiles. This is also true when one Target method passes its parameter on to another one. Core\Router::url finds the route when the program runs. It throws a RuntimeError when the method has no route.
A private route method passed from another class is E0471. An instance route method needs an object. Inside an instance method of its own class, Shop::show uses $this. From anywhere else, the route method must be static.
The route must be in your own program. A class from another module, under autoload links, is E0897. Write that link with Core\Router::url.
- A
privateroute method can only be passed from inside its own class. Your method gets acallablethat it can call, so the compiler checks who may call it. - A route of another module does not compile here. Write that link with
Core\Router::url.
An OpenAPI document
#[Core\Api] describes a route in the API document that nvs build --openapi writes. It goes on a method that has a #[Core\Route].
Most of the document comes from the code: the path, the parameters, their types and the return type. The /// comment above the method gives the summary and the description. #[Core\Api] adds the rest. tags: groups the operation, and security: names the scheme a client must use. errors: lists the error responses, and example: shows one response. operationId: sets the operation's name.
A parameter's type gives its schema. A Core\Time\Date is a string with the format date. A #[Core\Query] ?T $x = null is not required.
Novis checks #[Core\Api] against the code when it compiles. A class in errors: must exist, and every key in example: must be a property of the return type. Each name in security: must be declared by a #[Core\Api\Scheme] in your program.
The examples below add one tag, then errors and a security scheme, then a small API for a client generator. The fourth shows an example: that does not compile. The fifth shows dates and query values.
Tag a route for the api document
<?nvs// Shows how to describe a route for the generated API document. `nvs build// --openapi` writes that document for every route in the program. `tags:` puts// this operation in a named group, so a reader finds it beside the other// invoice operations.
class Invoices{ // The `///` line below is the summary and the description of this operation. /// Show one invoice. Looks the invoice up by its number. #[Core\Route(path: '/invoices/{number}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api(tags: ['Invoices'])] public function show(uint $number): string { return 'invoice ' . $number; }}
// A route is an ordinary method. You can call it directly.// This prints `invoice 1042`.Invoices $invoices = new Invoices();echo $invoices->show(1042), "\n";invoice 1042Name the errors and the security scheme
<?nvs// Shows how to say which errors an operation returns, and which security// scheme it needs. Each entry in `errors:` becomes one response in the// generated API document. Novis checks that the class you name exists.
// `#[Core\Api\Scheme]` declares the scheme that `security:` names.#[Core\Api\Scheme(name: 'bearer', type: Core\Api\SchemeType::Http, scheme: 'bearer', format: 'JWT')]class Auth{}
class NotFound extends RuntimeError{}
class Payments{ /// Show one payment. Returns the amount in cents. #[Core\Route(path: '/payments/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api( tags: ['Payments'], // A client of this API sends a bearer token with every request. security: ['bearer'], errors: [{ status: 404, type: NotFound::class }], )] public function show(uint $id): uint { if ($id == 0) { throw new NotFound('there is no payment 0'); } return $id * 100; }}
Payments $payments = new Payments();// This prints `700`.echo $payments->show(7), "\n";
// The error the document names is an ordinary error. Your code throws it and// catches it in the usual way.try { echo $payments->show(0), "\n";} catch (NotFound $error) { echo 'not found: ', $error->message, "\n";}700not found: there is no payment 0An orders api a client can be generated from
<?nvs// Shows a small API described well enough to generate a client from it. Every// operation has a summary, a group and an example of what it returns. `nvs// build --openapi` writes one document holding all of it, and a code generator// turns that document into a client library.
// The client sends a bearer token. The document describes it once, here.#[Core\Api\Scheme(name: 'bearer', type: Core\Api\SchemeType::Http, scheme: 'bearer')]class Auth{}
class Order{ public uint $id = 0; public string $customer = ''; public uint $totalCents = 0;}
class Orders{ /// Count the open orders. Returns how many are waiting to be shipped. #[Core\Route(path: '/orders', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api(tags: ['Orders'], security: ['bearer'])] public function index(): uint { return 3; }
/// Show one order. Looks the order up by its id. #[Core\Route(path: '/orders/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api( tags: ['Orders'], security: ['bearer'], // Every key here must be a property of the return type. Novis checks // this, so the example in the document cannot go out of date. example: { id: 7, customer: 'Ada Lovelace', totalCents: 4250 }, )] public function show(uint $id): Order { Order $order = new Order(); $order->id = $id; $order->customer = 'Ada Lovelace'; $order->totalCents = 4250; return $order; }}
Orders $orders = new Orders();echo 'open orders: ', $orders->index(), "\n";
Order $order = $orders->show(7);echo 'order ', $order->id, ' for ', $order->customer, "\n";echo 'total: ', $order->totalCents, " cents\n";open orders: 3order 7 for Ada Lovelacetotal: 4250 centsAn example must match the return type
<?nvs// Shows that `example:` is checked against the return type. `Order` has no// `price` property, so the program does not compile.// proof: compile-error
class Order{ public uint $id = 0;}
class Orders{ #[Core\Route(path: '/orders/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api(example: { id: 7, price: 4250 })] public function show(uint $id): Order { return new Order(); }}error[E0771]: `Order` declares no `price` --> 04-an-example-must-match-the-return-type.nvs:15:34 |15 | #[Core\Api(example: { id: 7, price: 4250 })] | ^^^^^^^^^^^ no such field = help: `example` is decoded as the return type. Every key must be a property of that class
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Optional query values and dates in the document
<?nvs// Shows how the API document describes a date, an optional query value and a// `bool` query value. `nvs build --openapi` reads each one from the parameter's// type.
class Reports{ /// List the orders of one day. #[Core\Route(path: '/reports/{day}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api(tags: ['Reports'])] public function orders( // In the document, `day` is a string with the format `date`. Core\Time\Date $day, // `?Core\Time\Instant` with `= null` is optional, so the document says it is not // required. Its schema is a string with the format `date-time`. #[Core\Query] ?Core\Time\Instant $since = null, // A `bool` query value is written `1` or `0`. The document gives it as an // integer with the values `0` and `1`. #[Core\Query] bool $shipped = false, ): string { string $from = $since?->toIso() ?? 'the start of the day'; return 'orders of ' . $day->toIso() . ' since ' . $from . ($shipped ? ', shipped only' : ''); }}
// A link to the route writes each value as text. This prints// `/reports/2026-03-14?since=2026-03-14T09%3A00%3A00Z&shipped=1`.echo Core\Router::url(Reports::orders, [ 'day' => Core\Time\Date::fromIso('2026-03-14'), 'since' => Core\Time\Instant::fromIso('2026-03-14T09:00:00Z'), 'shipped' => true,]), "\n";
// A route is an ordinary method. You can call it directly.Reports $reports = new Reports();echo $reports->orders(Core\Time\Date::fromIso('2026-03-14')), "\n";/reports/2026-03-14?since=2026-03-14T09%3A00%3A00Z&shipped=1orders of 2026-03-14 since the start of the dayDetails
nvs build --openapi main.nvs writes the document to standard output and runs nothing. The document's info.title is the file name without .nvs. info.version is the version in the nearest package.toml, found from the folder you run the command in. Without one, it is 0.0.0. A program with no #[Core\Route] writes no document. The command prints a message to standard error that says so, and exits with status 0. A program that does not compile writes no document either. The command prints the compile errors and exits with status 1. Some pairs of routes cannot both be in the document. /files/{path} and /files/{path...} both give the path /files/{path}, so they collide when they use the same HTTP method. /a/{id} and /a/{key} differ only in the name of the capture. OpenAPI treats them as one path, so they collide for any HTTP methods. For a collision, the command prints an error that names both routes. It writes no document.
The paths are sorted by their text, and the operations of one path by their HTTP method. Two builds of the same file give the same bytes. Each operation's operationId is the full name of its method, with dots: Shop.show, or App.Shop.show in the namespace App. When one method has several routes, each operationId gets the HTTP method in lowercase after a dot, such as Hook.receive.post and Hook.receive.put. #[Core\Api(operationId: 'listOrders')] sets the operationId yourself.
The first sentence of the /// comment is the summary. The rest of the comment is the description, and a blank /// line in it stays a blank line. A comment with no full stop is all summary. A method with no /// comment has neither.
Each capture is a parameter with "in": "path", and it is always required. Each #[Core\Query] parameter is a parameter with "in": "query". It is required when it has no default value. Each type has its own schema. An int is integer, and a uint is integer with a minimum of 0. A decimal is a string with the format decimal. An enum lists the names of its cases, and a set of allowed values such as 'x'|'y' lists those values. A bool query value is integer with the enum [0, 1]. A Core\Time\Date is a string with the format date, and a Core\Time\Instant is a string with the format date-time. A TimeOfDay or a DateTime is a string with no format, and a Core\Uuid is a string with the format uuid.
The 200 response has the schema of the return type when it is string, int, uint, float, bool or decimal. Every other return type has the empty schema {}. This includes a class, an array, an enum and a ?int. A void method has a 200 response with no content.
#[Core\Api] has five fields: tags, security, errors, example and operationId. Every field is optional, and #[Core\Api] with no list is allowed. Any other field is E0454. Each value must be written directly in the code, so "a" . "b" in tags is E0725. You can write #[Api(...)] after use Core\Api;. A static route method takes #[Core\Api] too.
Each check below gives E0771 when it fails. #[Core\Api] on a method with no #[Core\Route] is not allowed. tags and security must be arrays, even for one entry, and each entry must be a string. An errors entry needs both status and type, and status must be a number from 100 to 599. example must be an anonymous object. When the return type is a class, each key of example must be a property of that class.
A class in errors that does not exist is E0303. A built-in class such as RuntimeError works too. Each errors entry becomes a response under its status, and the response's description is the class name. An empty tags array writes no tags. Each name in security becomes its own entry in the operation's security list, with an empty list of scopes. Each name in security must be the name of an #[Core\Api\Scheme] on a class of the program. Any other name is E0886. Each scheme type needs its own fields: Http needs scheme, and ApiKey needs in and parameter. The example value is written into the 200 response beside its schema.
The examples above do not print the document. This file is one more route with #[Core\Api]:
<?nvs// This program declares a route with extra details for an OpenAPI document.
class Users{ /// Show one user. Looks the user up by id. #[Core\Route(path: '/users/{id}', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] #[Core\Api(tags: ['users'])] public function show(uint $id): string { return 'user ' . $id; }}
echo Core\Router::url(Users::show, ['id' => 7]), "\n";/users/7For this file, nvs build --openapi main.nvs prints a document with this operation:
"/users/{id}": { "get": { "description": "Looks the user up by id.", "operationId": "Users.show", "parameters": [ {"in": "path", "name": "id", "required": true, "schema": {"minimum": 0, "type": "integer"}} ], "responses": { "200": {"content": {"application/json": {"schema": {"type": "string"}}}, "description": "success"} }, "summary": "Show one user.", "tags": ["users"] }}More facts about the document:
- The
operationIdis the full name of the route method, with dots. It isUsers.showhere, andApp.Users.showin the namespaceApp.#[Core\Api(operationId: 'showUser')]sets your own. - Each name in
security:needs a#[Core\Api\Scheme]on a class of your program, such as#[Core\Api\Scheme(name: "bearer", type: Core\Api\SchemeType::Http, scheme: "bearer")]. The document lists each scheme undercomponents.securitySchemes. A name that no scheme declares does not compile. - When the method returns a class with
#[Core\Json\Derive], the response schema lists the JSON fields of that class. - When the method reads the body with
Core\Request::jsonAs<T>()orCore\Request::formFieldsAs<T>(), the document describes that body with the schema ofT. The call must be in the route method itself. A body that another method reads is not in the document. - The document’s
info.versionis theversionin the nearestpackage.toml. Without one, it is0.0.0. - Two routes can have the same path in the document, such as
/a/{id}and/a/{key}. Thennvs build --openapiprints an error that names both routes, and writes no document.
Do and don’t
Section titled “Do and don’t”- Do build links with
Core\Router::url, such asCore\Router::url(Users::show, ['id' => 7]). - Do check
accessAsonce, before theswitchthat calls the methods. - Do give a capture the type you need, such as
uint. The conversion is then done for you. - Don’t write a path by hand in a link. A typo in a method name does not compile.
- Don’t use
csrf: falseon a form that a browser sends.
