foil
700 byte framework agnostic universal router.
Features
- Simple
- Nestable
- Middleware
- Universal
Install
npm i foil --save
Usage
const app = app
Defining routes
Routes should be defined with both path
and payload
properties.
path
- a path representing the route, including named parameterspayload
- an object to be returned when the route is matched
const path = '/' const payload = // ... path payload
Parameters
Routes can be defined with simple parameters. When matched, these params will be
returned on the context
object. Only named parameters (:slug
) and wildcards
(*
) are supported at this time.
const app = app
Context
context
is created when a route is matched. It looks like this:
state: params: {} pathname: '' search: '' location: ''
Custom Context
You can add your own properties to context
when you create a router instance.
It will then be available to every resolved route.
const app = app
Nested routes
Routes can be nested by passing a route to the function returned from the parent route. Nested routes build on the paths of their parents.
This means that certain generic routes can be reused in different locations. The
code below results in four separate routes: /about
, /about/:slug
, /posts
,
and /posts/:slug
.
const About = const Posts = const Lightbox =
Middleware
foil
implements very simple "middleware". Middleware functions are defined
with the use
export from foil
.
Middleware are passed the complete context
of the route matched, plus a
handy redirect
method.
They are executed on each route transition for the route scope in which they are defined, and all nested scopes.
Below, the root
middleware will be called when the Home
or Posts
routes
are matched. When either Home
, Posts
or Post
are matched, both root
and
nested
will fire.
const root =
Redirects
Redirects are creating using middleware.
const redirectMiddleware = const app =
If a redirect is issued via redirect()
, the redirect
prop passed to
your app.resolve()
callback will contain to
and from
properties that tell
you where the redirect occurred:
app
Protected Routes
A route or a group of routes can also easily be protected using this same pattern.
const app =
Server Side Rendering
Create a new foil
instance on each request.
const server = server
Usage with Other UI Libraries
- React - @foil/react
About the Name
I like the word foil as a figurative term, as in to set off by contrast. In
the context of routing in React (which is my main motivation behind this
library, see @foil/react),
foil
is a bit of a departure from many of the more well established patterns.
Many thanks to jkuri for letting me use the npm package name! Very kind of him :)
License
MIT License © Eric Bailey