meteorhacks:flow-router-ssr

v2.0.1Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Flow Router Build Status Stories in Ready

Carefully Designed Client Side Router for Meteor.

Flow Router is a minimalistic router which only handles routing and subscriptions. You can't have any kind of reactive code inside the router. But there is a rich reactive API to watch changes in the routes.

TOC

Getting Started

Add Flow Router to your app:

meteor add meteorhacks:flow-router

Let's write our first route (add this file to lib/router.js):

1FlowRouter.route('/blog/:postId', {
2    subscriptions: function(params) {
3        console.log("subscribe and register this subscription as 'myPost'");
4        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
5    },
6    action: function(params) {
7        console.log("Yeah! We are on the post:", params.postId);
8    }
9});

Then visit /blog/my-post-id from the browser or invoke the following command from the browser console:

1FlowRouter.go('/blog/my-post-id');

Then you can see some messages printed in the console.

Routes Definition

Flow Router routes are very simple and based on the syntax of path-to-regexp which is used in both Express and iron:router.

Here's the syntax for a simple route:

1FlowRouter.route('/blog/:postId', {
2    // an array of middlewares (we'll discuss about this later on)
3    middlewares: [],
4
5    // define your subscriptions
6    subscriptions: function(params, queryParams) {
7       
8    },
9
10    // do some action for this route
11    action: function(params, queryParams) {
12        console.log("Params:", params);
13        console.log("Query Params:", queryParams);
14    },
15
16    name: "<name for the route>" // optional
17});

So, this route will be activated when you visit a url like below:

1FlowRouter.go('/blog/my-post?comments=on&color=dark');

After you've visit the route, this will be printed in the console:

Params: {postId: "my-post"}
Query Params: {comments: "on", color: "dark"}

For a single interaction, the router only runs once. That means, after you've visit a route, first it will call middlewares, then subscriptions and finally action. After that happens, none of those methods will be called again for that route visit.

You can define routes anywhere in the client directory. But, we recommend to add them in the lib directory. Then fast-render can detect subscriptions and send them for you (we'll talk about this is a moment).

Group Routes

You can group routes for better route organization. Here's an example:

1var adminRoutes = FlowRouter.group({
2  prefix: '/admin',
3  subscriptions: function() {
4    this.register('adminSettings', Meteor.subscribe('settings', {admin: true}));
5  },
6  middlewares: [
7    function(path, next) {
8      console.log('running group middleware');
9      next();
10    }
11  ]
12});
13
14// handling /admin route
15adminRoutes.route('/', {
16  action: function() {
17    FlowLayout.render('componentLayout', {content: 'admin'});
18  },
19  middlewares: [
20    function(path, next) {
21      console.log('running /admin middleware');
22      next();
23    }
24  ]
25});
26
27// handling /admin/posts
28adminRoutes.route('/posts', {
29  action: function() {
30    FlowLayout.render('componentLayout', {content: 'posts'});
31  }
32});

All of the options for the FlowRouter.group() are optional.

You can even have nested group routes as shown below:

1var adminRoutes = FlowRouter.group({
2    prefix: "/admin"
3});
4
5var superAdminRoutes = adminRoutes.group({
6    prefix: "/super"
7});
8
9// handling /admin/super/post
10superAdminRoutes.route('/post', {
11    action: function() {
12
13    }
14});

Subscription Management

Flow Router does only registration of subscriptions. It does not wait until subscription became ready. This is how to register a subscription.

1FlowRouter.route('/blog/:postId', {
2    subscriptions: function(params, queryParams) {
3        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
4    }
5});

We can also register global subscriptions like this:

1FlowRouter.subscriptions = function() {
2  this.register('myCourses', Meteor.subscribe('courses'));
3};

All these global subscriptions run on every route. So, pay special attention to names when registering subscriptions.

After you've registered your subscriptions, you can reactively check for the status of those subscriptions like this:

1Tracker.autorun(function() {
2    console.log("Is myPost ready?:", FlowRouter.subsReady("myPost"));
3    console.log("Does all subscriptions ready?:", FlowRouter.subsReady());
4});

So, you can use FlowRouter.subsReady inside template helpers to show the loading status and act accordingly.

FlowRouter.subsReady() with a callback

Sometimes, we need to use FlowRouter.subsReady() in places where an autorun is not available. One such example is inside an event handler. For such places, we can use the callback API of FlowRouter.subsReady().

1Template.myTemplate.events(
2   "click #id": function(){
3      FlowRouter.subsReady("myPost", function() {
4         // do something
5      });
6  }
7);

Arunoda has discussed more about Subscription Management in Flow Router in this blog post about Flow Router and Subscription Management.

He's showing how to build an app like this:

FlowRouter's Subscription Management

Fast Render

Flow Router has built in support for Fast Render.

  • meteor add meteorhacks:fast-render
  • Put router.js in a shared location. We suggest lib/router.js.

You can exclude Fast Render support by wrapping the subscription registration in an isClient block:

1FlowRouter.route('/blog/:postId', {
2    subscriptions: function(params, queryParams) {
3        // using Fast Render
4        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
5
6        // not using Fast Render
7        if(Meteor.isClient) {
8            this.register('data', Meteor.subscribe('bootstrap-data');
9        }
10    }
11});

Subscription Caching

You can also use Subs Manager for caching subscriptions on the client. We haven't done anything special to make it work. It should work as it works with other routers.

Rendering and Layout Management

Flow Router does not handle rendering or layout management. For that, you can use Flow Layout.

Then you can invoke the layout manager inside the action method in the router.

1FlowRouter.route('/blog/:postId', {
2    action: function(params) {
3        FlowLayout.render("mainLayout", {area: "blog"});
4    }
5});

Triggers

Triggers are the way flow-router allows you to perform tasks before enter into a route and after exit from a route.

Defining triggers for a route

Here's how you can define triggers for a route:

1FlowRouter.route('/home', {
2  // calls just before the action
3  triggersEnter: [trackRouteEntry],
4  action: function() {
5    // do something you like
6  },
7  // calls when when we decide to move to another route
8  // but calls before the next route started
9  triggersExit: [trackRouteClose]
10});
11
12function trackRouteEntry(context) {
13  // context is the output of `FlowRouter.current()`
14  Mixpanel.track("visit-to-home", context.queryParams);
15}
16
17function trackRouteClose(context) {
18  Mixpanel.track("move-from-home", context.queryParams);
19}

Defining triggers for a group route

This is how you can define triggers to a group definition.

1var adminRoutes = FlowRouter.group({
2  prefix: '/admin',
3  subscriptions: function() {
4    this.register('adminSettings', Meteor.subscribe('settings', {admin: true}));
5  },
6  triggersEnter: [trackRouteEntry],
7  triggersExit: [trackRouteEntry]
8});

You can add triggers to individual routes in the group too.

Defining Trigges Globally

You can also define triggers globally. Here's how to do it:

1FlowRouter.triggers.enter([cb1, cb2]);
2FlowRouter.triggers.exit([cb1, cb2]);
3
4// filtering
5FlowRouter.triggers.enter([trackRouteEntry], {only: ["home"]});
6FlowRouter.triggers.exit([trackRouteExit], {except: ["home"]});

As you can see from the last two examples, you can filter routes using the only or except keywords. But, you can't use both only and except at once.

If you'd like to learn more about triggers and design decisions, visit here.

Redirecting With Triggers

You can redirect to a different route using triggers. You can do it from both enter and exit triggers. See how to do it:

1FlowRouter.route('/', {
2  triggersEnter: [function(context, redirect) {
3    redirect('/some-other-path');
4  }],
5  action: function(_params) {
6    throw new Error("this should not get called");
7  }
8});

Every trigger callback comes with a second argument. It's a function where you can used to redirect to a different route. Redirect also has few properties to make sure it's not blocking the router.

  • redirect must be called with an URL
  • redirect must be called within the same eventloop cycle (no async or called inside a Tracker)
  • redirect cannot be called multiple times

Check this PR to learn more about our redirect API.

Middlewares

Right now middlewares are deprecated. Use triggers instead. Triggers are very similar to middlewares, but triggers don't have a next() argument. So, you've no way to block or wait the route.

Sometimes, you need to invoke some tasks just before entering the route. That's where middlewares come in. Here are some of the use cases for middlewares:

  • Route redirecting
  • Analytics
  • Initialization tasks

Below is an example of implementing simple redirection logic with middlewares. It will redirect a user to the sign-in page if they are not logged in.

1
2FlowRouter.route('/apps/:appId', {
3    middlewares: [requiredLogin],
4    subscriptions: function(params) {
5        
6    },
7    action: function(params) {
8
9    }
10});
11
12function requiredLogin(path, next) {
13  // this works only because the use of Fast Render
14  var redirectPath = (!Meteor.userId())? "/sign-in" : null;
15  next(redirectPath);
16}

You can also write global middlewares like this:

1FlowRouter.middleware(trackingMiddleware);
2
3function trackingMiddleware(path, next) {
4    console.log("tracking path:", path);
5    next();
6}

Not Found Routes

You can configure Not Found routes like this:

1FlowRouter.notFound = {
2    // Subscriptions registered here don't have Fast Render support.
3    subscriptions: function() {
4      
5    },
6    action: function() {
7      
8    }
9};

API

Flow Router has a rich API to help you to navigate the router and reactively get information from the router.

FlowRouter.getParam(paramName);

Reactive function which you can use to get a parameter from the URL.

1// route def: /apps/:appId
2// url: /apps/this-is-my-app
3
4var appId = FlowRouter.getParam("appId");
5console.log(appId); // prints "this-is-my-app"

FlowRouter.getQueryParam(queryStringKey);

Reactive function which you can use to get a value from the queryString.

1// route def: /apps/:appId
2// url: /apps/this-is-my-app?show=yes&color=red
3
4var color = FlowRouter.getQueryParam("color");
5console.log(color); // prints "red"

FlowRouter.path(pathDef, params, queryParams)

Generate a path from a path definition. Both params and queryParams are optional.

Special characters in params and queryParams will be urlencoded.

1var pathDef = "/blog/:cat/:id";
2var params = {cat: "met eor", id: "abc"};
3var queryParams = {show: "y+e=s", color: "black"};
4
5var path = FlowRouter.path(pathDef, params, queryParams);
6console.log(path); // prints "/blog/met%20eor/abc?show=y%2Be%3Ds&color=black"

If there are no params or queryParams, this will simply return the pathDef as it is.

Using Route name instead of the pathDef

You can also use the route's name instead of the pathDef. Then, Flow Router will pick the pathDef from the given route. See the following example:

1FlowRouter.route("/blog/:cat/:id", {
2    name: "blogPostRoute",
3    action: function(params) {
4        //...
5    }
6})
7
8var params = {cat: "meteor", id: "abc"};
9var queryParams = {show: "yes", color: "black"};
10
11var path = FlowRouter.path("blogPostRoute", params, queryParams);
12console.log(path); // prints "/blog/meteor/abc?show=yes&color=black"

FlowRouter.go(pathDef, params, queryParams);

This will get the path via FlowRouter.path based on the arguments and re-route to that path.

You can call FlowRouter.go like this as well:

1FlowRouter.go("/blog");

FlowRouter.setParams(newParams)

This will change the current params with the newParams and re-route to the new path.

1// route def: /apps/:appId
2// url: /apps/this-is-my-app?show=yes&color=red
3
4FlowRouter.setParams({appId: "new-id"});
5// Then the user will be redirected to the following path
6//      /apps/new-id?show=yes&color=red

FlowRouter.setQueryParams(newQueryParams)

Just like FlowRouter.setParams, but for queryString params.

To remove a query param set it to null like below:

1FlowRouter.setQueryParams({paramToRemove: null});

FlowRouter.getRouteName()

To get the name of the route reactively.

1Tracker.autorun(function() {
2  var routeName = FlowRouter.getRouteName();
3  console.log("Current route name is: ", routeName);
4});

FlowRouter.current()

Get the current state of the router. This API is not reactive. If you need to watch the changes in the path simply use FlowRouter.watchPathChange().

This gives an object like this:

1// route def: /apps/:appId
2// url: /apps/this-is-my-app?show=yes&color=red
3
4var current = FlowRouter.current();
5console.log(current);
6
7// prints following object
8// {
9//     path: "/apps/this-is-my-app?show=yes&color=red",
10//     params: {appId: "this-is-my-app"},
11//     queryParams: {show: "yes", color: "red"}
12//     route: {name: "name-of-the-route"}
13// }

FlowRouter.watchPathChange()

Reactively watch the changes in the path. If you need to simply get the params or queryParams use dedicated APIs like FlowRouter.getQueryParam().

1Tracker.autorun(function() {
2  FlowRouter.watchPathChange();
3  var currentContext = FlowRouter.current();
4  // do anything with the current context
5  // or anything you wish
6});

FlowRouter.reactiveCurrent() [Deprecated]

This API is deprecated. Use FlowRouter.watchPathChange instead. This API won't included in the next major release. (2.x.x)

FlowRouter.withReplaceState(fn)

Normally, all the route changes made via APIs like FlowRouter.go and FlowRouter.setParams() add a URL item to the browser history. For example, run the following code:

1FlowRouter.setParams({id: "the-id-1"});
2FlowRouter.setParams({id: "the-id-2"});
3FlowRouter.setParams({id: "the-id-3"});

Now you can hit the back button of your browser two times. This is normal behaviour since users may click the back button and expect to see the previous state of the app.

But sometimes, this is not something you want. You don't need to pollute the browser history. Then, you can use the following syntax.

1FlowRouter.withReplaceState(function() {
2  FlowRouter.setParams({id: "the-id-1"});
3  FlowRouter.setParams({id: "the-id-2"});
4  FlowRouter.setParams({id: "the-id-3"});
5});

Now, there is no item in the browser history. Just like FlowRouter.setParams, you can use any FlowRouter API inside FlowRouter.withReplaceState.

We named this function as withReplaceState because, replaceState is the underline API used for this functionality. Read more about replace state & the history API.

FlowRouter.reload()

FlowRouter routes are idempotent. That means, even if you call FlowRouter.go() to the same URL multiple times, it only activates in the first run. This is also true for directly clicking on paths.

So, if you really need to reload the route, this is the API you want.

FlowRouter.wait() and FlowRouter.initialize()

By default, Flow Router initilize the routing process in a Meteor.startup() callback. This works for most of the apps. But, some apps have custom initializations and FlowRouter needs to initialize after that.

So, that's where FlowRouter.wait() comes to save you. You need to call it directly inside your JavaScript file. After that, whenever your app is ready call FlowRouter.initialize().

eg:-

1// file: app.js
2FlowRouter.wait();
3WhenEverYourAppIsReady(function() {
4  FlowRouter.initialize();
5});

For more information visit issue #180.

Difference with Iron Router

Flow Router and Iron Router are two different routers. Iron Router tries to be a full featured solution. It tries to do everything including routing, subscriptions, rendering and layout management.

Flow Router is a minimalistic solution focused on routing with UI performance in mind. It exposes APIs for related functionality.

Let's learn more about the differences:

Rendering

Flow Router doesn't handle rendering. By decoupling rendering from the router it's possible to use any rendering framework, such as Flow Layout to render with Blaze's Dynamic Templates, React, or Polymer. Rendering calls are made in the the route's action.

Subscriptions

With Flow Router, you can register subscriptions, but there is no concept like Iron Router's waitOn. Instead Flow Router provides a reactive API to check the state of subscriptions. You can use that to achieve similar functionality in the template layer.

Reactive Content

In Iron Router you can use reactive content inside the router, but any hook or method can re-run in unpredictable manner. Flow Router limits reactive data sources to a single run when it is first called.

We think, that's the way to go. Router is just a user action. We can work with reactive content in the rendering layer.

router.current() is evil

Router.current() is evil. Why? Let's look at following example. Imagine we've a route like this in our app:

/apps/:appId/:section

Now let's say, we need to get appId from the URL. Then we will do, something like this in Iron Router.

1Templates['foo'].helpers({
2    "someData": function() {
3        var appId = Router.current().params.appId;
4        return doSomething(appId);
5    }
6});

Okay. Let's say we changed :section in the route. Oh then above helper also gets rerun. Even if we add a query param to the URL, it gets rerun. That's because Router.current() looks for changes in the route(or URL). But in any of above cases, appId didn't get changed.

Because of this, a lot parts of our app gets re run and re-rendered. This creates unpredictable rendering behavior in our app.

Flow Router fixes this issue simply by providing the Router.getParam() API. See how to use it:

1Templates['foo'].helpers({
2    "someData": function() {
3        var appId = FlowRouter.getParam('appId');
4        return doSomething(appId);
5    }
6});

No data context

Flow Router does not have a data context. Data context has the same problem as reactive .current(). We believe, it'll possible to get data directly in the template (component) layer.

Built in Fast Render Support

Flow Router has built in Fast Render support. Just add Fast Render to your app and it'll work. Nothing to change in the router.

For more information check docs.

Server Side Routing

Flow Router is a client side router and it does not support sever side routing at all. But subscriptions run on the server to enabled Fast Render support.

Reason behind that

Meteor is not a traditional framework where you can send HTML directly from the server. Meteor needs to send a special set of HTML to the client initially. So, you can't directly send something to the client your self.

Also, in the server we need look for different things compared with the client. For example:

  • In server we've to deal with headers.
  • In server we've to deal with methods like GET, POST, etc.
  • In server we've Cookies

So, it's better to use a dedicated server-side router like meteorhacks:picker. It supports connect and express middlewares and has a very easy to use route syntax.

Server Side Rendering (SSR)

Although, we don't have server side routes, we will have server side rendering support. We've some initial plans to achieve SSR and it's the main feature of version 3.0.

We may have our own initial HTML rendering system to allow SSR bypassing meteor's default layout.