Giter VIP home page Giter VIP logo

flow-router's Introduction

FlowRouter Build Status Stories in Ready

Carefully Designed Client Side Router for Meteor.

FlowRouter is a very simple router for Meteor. It does routing for client-side apps and does not handle rendering itself.

It exposes a great API for changing the URL and reactively getting data from the URL. However, inside the router, it's not reactive. Most importantly, FlowRouter is designed with performance in mind and it focuses on what it does best: routing.

We've released 2.0 and follow this migration guide if you are already using FlowRouter.

TOC

Meteor Routing Guide

Meteor Routing Guide is a completed guide into routing and related topics in Meteor. It talks about how to use FlowRouter properly and use it with Blaze and React. It also shows how to manage subscriptions and implement auth logic in the view layer.

Meteor Routing Guide

Getting Started

Add FlowRouter to your app:

meteor add kadira:flow-router

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

FlowRouter.route('/blog/:postId', {
    action: function(params, queryParams) {
        console.log("Yeah! We are on the post:", params.postId);
    }
});

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

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

Then you can see some messages printed in the console.

Routes Definition

FlowRouter 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:

FlowRouter.route('/blog/:postId', {
    // do some action for this route
    action: function(params, queryParams) {
        console.log("Params:", params);
        console.log("Query Params:", queryParams);
    },

    name: "<name for the route>" // optional
});

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

FlowRouter.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 triggers, 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:

var adminRoutes = FlowRouter.group({
  prefix: '/admin',
  name: 'admin',
  triggersEnter: [function(context, redirect) {
    console.log('running group triggers');
  }]
});

// handling /admin route
adminRoutes.route('/', {
  action: function() {
    BlazeLayout.render('componentLayout', {content: 'admin'});
  },
  triggersEnter: [function(context, redirect) {
    console.log('running /admin trigger');
  }]
});

// handling /admin/posts
adminRoutes.route('/posts', {
  action: function() {
    BlazeLayout.render('componentLayout', {content: 'posts'});
  }
});

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

You can even have nested group routes as shown below:

var adminRoutes = FlowRouter.group({
    prefix: "/admin",
    name: "admin"
});

var superAdminRoutes = adminRoutes.group({
    prefix: "/super",
    name: "superadmin"
});

// handling /admin/super/post
superAdminRoutes.route('/post', {
    action: function() {

    }
});

You can determine which group the current route is in using:

FlowRouter.current().route.group.name

This can be useful for determining if the current route is in a specific group (e.g. admin, public, loggedIn) without needing to use prefixes if you don't want to. If it's a nested group, you can get the parent group's name with:

FlowRouter.current().route.group.parent.name

As with all current route properties, these are not reactive, but can be combined with FlowRouter.watchPathChange() to get group names reactively.

Rendering and Layout Management

FlowRouter does not handle rendering or layout management. For that, you can use:

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

FlowRouter.route('/blog/:postId', {
    action: function(params) {
        BlazeLayout.render("mainLayout", {area: "blog"});
    }
});

Triggers

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

Defining triggers for a route

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

FlowRouter.route('/home', {
  // calls just before the action
  triggersEnter: [trackRouteEntry],
  action: function() {
    // do something you like
  },
  // calls when we decide to move to another route
  // but calls before the next route started
  triggersExit: [trackRouteClose]
});

function trackRouteEntry(context) {
  // context is the output of `FlowRouter.current()`
  Mixpanel.track("visit-to-home", context.queryParams);
}

function trackRouteClose(context) {
  Mixpanel.track("move-from-home", context.queryParams);
}

Defining triggers for a group route

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

var adminRoutes = FlowRouter.group({
  prefix: '/admin',
  triggersEnter: [trackRouteEntry],
  triggersExit: [trackRouteEntry]
});

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

Defining Triggers Globally

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

FlowRouter.triggers.enter([cb1, cb2]);
FlowRouter.triggers.exit([cb1, cb2]);

// filtering
FlowRouter.triggers.enter([trackRouteEntry], {only: ["home"]});
FlowRouter.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:

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

Every trigger callback comes with a second argument: a function you can use 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 event loop cycle (no async or called inside a Tracker)
  • redirect cannot be called multiple times

Check this PR to learn more about our redirect API.

Stopping the Callback With Triggers

In some cases, you may need to stop the route callback from firing using triggers. You can do this in before triggers, using the third argument: the stop function. For example, you can check the prefix and if it fails, show the notFound layout and stop before the action fires.

var localeGroup = FlowRouter.group({
  prefix: '/:locale?',
  triggersEnter: [localeCheck]
});

localeGroup.route('/login', {
  action: function (params, queryParams) {
    BlazeLayout.render('componentLayout', {content: 'login'});
  }
});

function localeCheck(context, redirect, stop) {
  var locale = context.params.locale;

  if (locale !== undefined && locale !== 'fr') {
    BlazeLayout.render('notFound');
    stop();
  }
}

Note: When using the stop function, you should always pass the second redirect argument, even if you won't use it.

Not Found Routes

You can configure Not Found routes like this:

FlowRouter.notFound = {
    // Subscriptions registered here don't have Fast Render support.
    subscriptions: function() {

    },
    action: function() {

    }
};

API

FlowRouter 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.

// route def: /apps/:appId
// url: /apps/this-is-my-app

var appId = FlowRouter.getParam("appId");
console.log(appId); // prints "this-is-my-app"

FlowRouter.getQueryParam(queryStringKey);

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

// route def: /apps/:appId
// url: /apps/this-is-my-app?show=yes&color=red

var color = FlowRouter.getQueryParam("color");
console.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 URL encoded.

var pathDef = "/blog/:cat/:id";
var params = {cat: "met eor", id: "abc"};
var queryParams = {show: "y+e=s", color: "black"};

var path = FlowRouter.path(pathDef, params, queryParams);
console.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, FlowRouter will pick the pathDef from the given route. See the following example:

FlowRouter.route("/blog/:cat/:id", {
    name: "blogPostRoute",
    action: function(params) {
        //...
    }
})

var params = {cat: "meteor", id: "abc"};
var queryParams = {show: "yes", color: "black"};

var path = FlowRouter.path("blogPostRoute", params, queryParams);
console.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:

FlowRouter.go("/blog");

FlowRouter.url(pathDef, params, queryParams)

Just like FlowRouter.path, but gives the absolute url. (Uses Meteor.absoluteUrl behind the scenes.)

FlowRouter.setParams(newParams)

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

// route def: /apps/:appId
// url: /apps/this-is-my-app?show=yes&color=red

FlowRouter.setParams({appId: "new-id"});
// Then the user will be redirected to the following path
//      /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:

FlowRouter.setQueryParams({paramToRemove: null});

FlowRouter.getRouteName()

To get the name of the route reactively.

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

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:

// route def: /apps/:appId
// url: /apps/this-is-my-app?show=yes&color=red

var current = FlowRouter.current();
console.log(current);

// prints following object
// {
//     path: "/apps/this-is-my-app?show=yes&color=red",
//     params: {appId: "this-is-my-app"},
//     queryParams: {show: "yes", color: "red"}
//     route: {pathDef: "/apps/:appId", name: "name-of-the-route"}
// }

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().

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

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:

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

Now you can hit the back button of your browser two times. This is normal behavior 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.

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

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, FlowRouter initializes 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:-

// file: app.js
FlowRouter.wait();
WhenEverYourAppIsReady(function() {
  FlowRouter.initialize();
});

For more information visit issue #180.

FlowRouter.onRouteRegister(cb)

This API is specially designed for add-on developers. They can listen for any registered route and add custom functionality to FlowRouter. This works on both server and client alike.

FlowRouter.onRouteRegister(function(route) {
  // do anything with the route object
  console.log(route);
});

Let's say a user defined a route like this:

FlowRouter.route('/blog/:post', {
  name: 'postList',
  triggersEnter: [function() {}],
  subscriptions: function() {},
  action: function() {},
  triggersExit: [function() {}],
  customField: 'customName'
});

Then the route object will be something like this:

{
  pathDef: '/blog/:post',
  name: 'postList',
  options: {customField: 'customName'}
}

So, it's not the internal route object we are using.

Subscription Management

For Subscription Management, we highly suggest you to follow Template/Component level subscriptions. Visit this guide for that.

FlowRouter also has it's own subscription registration mechanism. We will remove this in version 3.0. We don't remove or deprecate it in version 2.x because this is the easiest way to implement FastRender support for your app. In 3.0 we've better support for FastRender with Server Side Rendering.

FlowRouter only deals with registration of subscriptions. It does not wait until subscription becomes ready. This is how to register a subscription.

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

We can also register global subscriptions like this:

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

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:

Tracker.autorun(function() {
    console.log("Is myPost ready?:", FlowRouter.subsReady("myPost"));
    console.log("Are all subscriptions ready?:", FlowRouter.subsReady());
});

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().

Template.myTemplate.events({
   "click #id": function(){
      FlowRouter.subsReady("myPost", function() {
         // do something
      });
  }
});

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

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

FlowRouter's Subscription Management

Fast Render

FlowRouter 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:

FlowRouter.route('/blog/:postId', {
    subscriptions: function(params, queryParams) {
        // using Fast Render
        this.register('myPost', Meteor.subscribe('blogPost', params.postId));

        // not using Fast Render
        if(Meteor.isClient) {
            this.register('data', Meteor.subscribe('bootstrap-data');
        }
    }
});

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.

IE9 Support

FlowRouter has IE9 support. But it does not ship the HTML5 history polyfill out of the box. That's because most apps do not require it.

If you need to support IE9, add the HTML5 history polyfill with the following package.

meteor add tomwasd:history-polyfill

Hashbang URLs

To enable hashbang urls like mydomain.com/#!/mypath simple set the hashbang option to true in the initialize function:

// file: app.js
FlowRouter.wait();
WhenEverYourAppIsReady(function() {
  FlowRouter.initialize({hashbang: true});
});

Prefixed paths

In cases you wish to run multiple web application on the same domain name, youโ€™ll probably want to serve your particular meteor application under a sub-path (eg example.com/myapp). In this case simply include the path prefix in the meteor ROOT_URL environment variable and FlowRouter will handle it transparently without any additional configuration.

Add-ons

Router is a base package for an app. Other projects like useraccounts should have support for FlowRouter. Otherwise, it's hard to use FlowRouter in a real project. Now a lot of packages have started to support FlowRouter.

So, you can use your your favorite package with FlowRouter as well. If not, there is an easy process to convert them to FlowRouter.

Add-on API

We have also released a new API to support add-on developers. With that add-on packages can get a notification, when the user created a route in their app.

If you've more ideas for the add-on API, let us know.

Difference with Iron Router

FlowRouter 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.

FlowRouter 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

FlowRouter doesn't handle rendering. By decoupling rendering from the router it's possible to use any rendering framework, such as Blaze Layout to render with Blaze's Dynamic Templates. Rendering calls are made in the the route's action. We have a layout manager for React as well.

Subscriptions

With FlowRouter, we highly suggest using template/component layer subscriptions. But, if you need to do routing in the router layer, FlowRouter has subscription registration mechanism. Even with that, FlowRouter never waits for the subscriptions and view layer to do it.

Reactive Content

In Iron Router you can use reactive content inside the router, but any hook or method can re-run in an unpredictable manner. FlowRouter 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 have 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.

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

Let's say we changed :section in the route. Then the above helper also gets rerun. 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 get re-run and re-rendered. This creates unpredictable rendering behavior in our app.

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

Templates['foo'].helpers({
    "someData": function() {
        var appId = FlowRouter.getParam('appId');
        return doSomething(appId);
    }
});

No data context

FlowRouter 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

FlowRouter 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

FlowRouter is a client side router and it does not support server side routing at all. But subscriptions run on the server to enable 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 yourself.

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

  • In the server we have to deal with headers.
  • In the server we have to deal with methods like GET, POST, etc.
  • In the server we have 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

FlowRouter 3.0 will have server side rendering support. We've already started the initial version and check our ssr branch for that.

It's currently very usable and Kadira already using it for https://kadira.io

Better Initial Loading Support

In Meteor, we have to wait until all the JS and other resources send before rendering anything. This is an issue. In 3.0, with the support from Server Side Rendering we are going to fix it.

Migrating into 2.0

Migrating into version 2.0 is easy and you don't need to change any application code since you are already using 2.0 features and the APIs. In 2.0, we've changed names and removed some deprecated APIs.

Here are the steps to migrate your app into 2.0.

Use the New FlowRouter Package

  • Now FlowRouter comes as kadira:flow-router
  • So, remove meteorhacks:flow-router with : meteor remove meteorhacks:flow-router
  • Then, add kadira:flow-router with meteor add kadira:flow-router

Change FlowLayout into BlazeLayout

  • We've also renamed FlowLayout as BlazeLayout.
  • So, remove meteorhacks:flow-layout and add kadira:blaze-layout instead.
  • You need to use BlazeLayout.render() instead of FlowLayout.render()

Stop using deprecated Apis

  • There is no middleware support. Use triggers instead.
  • There is no API called .reactiveCurrent(), use .watchPathChange() instead.
  • Earlier, you can access query params with FlowRouter.current().params.query. But, now you can't do that. Use FlowRouter.current().queryParams instead.

flow-router's People

Contributors

adambharris avatar alanning avatar arunoda avatar ccorcos avatar d4h0 avatar dandv avatar delgermurun avatar elidoran avatar frozeman avatar jackzampolin avatar kelbongoo avatar kuil09 avatar lgollut avatar maksimabramchuk avatar mikowals avatar mitar avatar mquandalle avatar pahans avatar patrickml avatar paulmolluzzo avatar petrometro avatar primigenus avatar ramyelkest avatar rhyslbw avatar richsilv avatar sprohaska avatar thani-sh avatar vladshcherbin avatar woogenius avatar yehchuonglong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flow-router's Issues

Helper methods for router

Add these essential helper methods

// generate a path according to this 
FlowRouter.path('/courses/:courseId', {courseId: 100});

// generate a path and route to that
FlowRouter.go('/courses/:courseId', {courseId: 10});

// If this route has this key, change it and re-route
FlowRouter.setParams({key: value})

// Get the query string param for key
FlowRouter.getQueryParam(key)

// Set this query string params and re-route
FlowRouter.setQueryParams(key: value})

handle 404

  • throw an error if no route is found for a path
  • need a way to handle a 404

Current path is sometimes redirected to / after Hot Code Reload

I am having trouble with the Hot Code Reload sending the app to / instead of its current path. I've been trying to figure it out now and again and have yet to do so.

Anyone else run into this trouble? Does it depend on which files were changed to trigger the HCR?

Sometimes it works as it's supposed to.
Other times it redirects to root (often).
It always seems to run twice.

I have Chrome set to preserve the console so I see the "Navigated to" message and then see two route actions run.

After running circles around this one for hours I am still unable to identify exactly what causes the router to change the path. Suggestions on how to hook into the router solely for debugging to see what's going on?

Perhaps it's something with Meteor's HCR automatically doing a login again? Perhaps sometimes the requiredLogin middleware runs and reroutes the user before the auto-login finishes?

getParam API and reactivity

We need an API to get params. Currently we are depending on the Router.current() for that.
So, for any URL changes, app will get re-rendered. So can it by giving an api like below.

FlowRouter.getParam('key');

Pass FlowRouter.current() to both middleware and action ?

Right now middleware gets path only and action gets params and queryParams.

I'm thinking it makes sense to instead pass the 'current' object to both of those. We can get all three objects from that (path, params, queryParams).

I noticed I'm doing FlowRouter.current() in action() to get the whole path. I'm sure it seems like an action() will already know its path, but, with params and queryParams involved it changes.

Also, in middleware I use FlowRouter.getParam because it only has path.

It seems it would be consistent to always provide the current object (FlowRouter.current()).

What are your thoughts?

Page reload on route change

Hello arunoda,

I'm trying to switch from IronRouter to FlowRouter. I am using FlowLayout aswell.
Here is my issue. Since there is no support for IronRouter {{pathFor}} functionnality like, yet, i am writing my links directly like this <a href="/signin">Sign in</a>

Problem is when i click on a link, the page reload completely. This looks strange for me because the layout is the same for the views, only the template change.

My layout looks like this:

<template name="externalFormLayout">
    <div id="external-form">
        {{> Template.dynamic template=main}}
    </div>
</template>

And the routes:

_signin_

FlowRouter.route('/signin', {
    action: function (params) {
        FlowLayout.render('externalFormLayout', {
            main: 'signinTemplate'
        });
    }
});

_signup_

FlowRouter.route('/signup', {
    action: function (params) {
        FlowLayout.render('externalFormLayout', {
            main: 'signupTemplate'
        });
    }
});

Is it a FlowRouter or a FlowLayout error?

Regards,

William

Flow Router Version 2.X

We created flow-router for our internal use and tried our different concepts. But, we forget to bring some of the coolest features IR had. And also, we can make add more features make sure using the router is simple.

Even though, we add more features we need to make sure few things here are they:

  • We never use tracker inside the router (exception is for managing subscriptions)
  • We never use any kind of rendering engines
  • We never want to support REST apis (but, we can have server side rendering support)

You can't add comment on this thread. But subscribe for updates. I'll post about when things will get merged into master.

FlowRouter.route must start with `/`

I spent a little while trying to debug this:

FlowRouter.route('/unit/:unitId') //works
FlowRouter.route('unit/:unitId') //does not work and does not throw an error

If the route does not start with a forward slash it does not work. If this is the intended behavior can we get an error? Or is this supported in a way that I am not thinking of?

Fast-Render + React

Hey there, I've been playing around with React lately and I've been using flow-router instead of iron-router because its way less opinionated (about blaze, particularly).

Anyways, I'm curious how I could get server-side rendering working. React has this method React.renderToString that should make it easy for SSR. This is clearly incomplete, but here's the idea:

https://github.com/ccorcos/meteor-react/blob/master/examples/SSR/main.jsx

I was looking around the fast-render code, and it looks like it relies on (1) subscriptions through flow-router, and (2) Meteor.subscribe. I'd like to use a React mixin to do subscriptions from within the React classes and I'd also like to use subs-manager.

Any suggestions on where/how to get started with this?

Thanks

Naming route

How about naming route?

FlowRouter.route('/blog/:postId', {
    name: 'blogDetail',
    action: function(params) {
        console.log("Yeah! We are on the post:", params.postId);
    }
});

use like this:

FlowRouter.go('blogDetail', params);
FlowRouter.path('blogDetail', params);

We can achieve it by other way. Using something like name => path mapping in project. But I think it's nice to have builtin.

Authentication middleware

Hello arunoda,

Continuing to try to port my IronRouter code to FlowRouter, i am facing a problem with middlewares.
With IronRouter, to ensure that a user was logged-in, i was using this code:


Iron.Router.plugins.auth = function (router, options) {
    router.onBeforeAction(function () {
        if (!Meteor.user() && !Meteor.loggingIn()) {
            if (Router.current() && Router.current().route)
                Session.set('returnTo', Router.current().route.getName());
            Router.go(options.authRoute);
        }
        this.next();
    }, {
        except: [
            'signin',
            'signup',
            'lostPassword',
            'resetPassword',
            'verifyEmail'
        ]
    });
};

Now, to switch to FlowRouter, i rewrited my code like this:

var exceptions = [
    '/signin',
    '/signup',
    '/lost-password',
    '/reset-password',
    '/verify-email'
];

FlowRouter.middleware(function (path, next) {
    console.log(path);
    if (!_.contains(exceptions, path)) {
        if (!Meteor.userId()) {
            Session.set('returnTo', path);
            next('/signin');
        }
    }
    next();
});

The main problem, if for routes reset-password and verify-email. Thoses routes accept a parameter token, and the this is the problem. I can't predict this token, ans so, i can't compare with the routes in the exceptions array.

Of course, i could've split the path to keep only the first part of the route, but it will complexify the code.

This should be easy with named routes to handle this issue. Another way would be to provide path and params to middlewared callbacks separately.

What do you think ?

Best regards,

William

Using reactive value in middlewares

I have login required middleware something like it:

function requiredLogin(path, next) {
  var redirectPath = (!Meteor.userId())? "/sign-in" : null;
  next(redirectPath);
}

Since Meteor.userId() reactive, when I go to login required router, redirected to /sign-in. Even when I logged in. How did you solve this kind of issue? Do I have to use fast-render?

It's annoying especially in development. Because on every hot code push reload, it redirects to sign-in.

page.js context?

Is it possible to get access to the page.js context?

I'm curious about using page.js's context to save route specific state for my application.

Best pattern to handle subscription updates after login & logout events

Hi, thanks for your work!
I would like to try out flow router in my application, but after reading the documentation it is still not completely clear to me, what to do if a user logs in, logs out (and maybe logs in as a different user after that). In iron router, the page reloaded "all by itself" if one used Meteor.user() in the route action or in waitOn. I have some user-specific settings that I use for some subscriptions. If a user logs in, these subscriptions have to be updated. Do I have to use an autorun somewhere in my application code to check for that and then reload the page? Or is there a better way to do that?

Setting query params on path with optional last param causes build up of question marks

Configured path in FlowRouter:

/app/data/:cat?

After first visit to that route the browser location shows:

/app/data

After setting query params via console {priority: '1', status='open'} the browser location is:

/app/data/??priority=1&status=open

And FlowRouter.getQueryParam("priority") will not return value '1'.

Repeat the setQueryParams again (with same values), and it is now:

/app/data/???priority=1&status=open&priority=1

Each subsequent setQueryParams adds another question mark whether I use new query params or the same ones. The question marks just build up.

When I navigate to another route they are cleared out.

When I remove the optional parameter from the route path this issue goes away.

When it's showing /app/data and I set the param with setParams({cat:'blah'}) the browser location shows:

/app/data/blah?

So, an optional last param causes a question mark to show.
And, setting query params on it causes a build up of question marks.

Why does flow router change the url?

Hello. Now I'm applying flow router instead of iron router on our service. It's pretty good and well working. Thanks for implementing beautiful router.

I have a question. Why does flow router change url? is this bug?
When i access below page by url, Flow router changes

  • /foo? -> /foo
  • /foo?a=b%26c&d=e -> /foo?a=b&c&d=e

Thanks in advance.

Hash support?

Does flow router support url hashes?

I'm considering the use of hashes as a way to control the UI (i.e. show/hide modals) of a single page (single route). This is a pattern that Iron Router does a poor job of explaining but i believe is a very common pattern. Thanks

Routes by name?

FlowRouter.route('/blog/:postId')

I'm getting an error

There is no route for the path: /blog

How can I use FlowRouter.go?

FlowRouter.go('/blog', {postId:postId})?
FlowRouter.go('blog', {postId:postId})?
FlowRouter.go('/blog/'+postId)?

Before hook and route name?

I know this is still a work in progress but I hope to add support for flow to kestanous:candid and kestanous:herald. Are there thoughts and/or options for the following?

Candid will need some kind of before hook that tells it what the current route is, and if it should stop the route (this may work at the component level as well).

Herald will just need to know the current route reactively (to mark notifications as read) and be able to take a user to a route (this may even just trigger some logic, it depends on flow).

No rush on replying, just try to get in the queue ^_^

Redirect to login after logging out

Feels like a total noobie question, but trying flow-router out instead of IR (hopes it gives a little bit less overhead-feeling). In the IR situation, I had before-hooks, that checked if the user is logged in. After logging out (e.g. Meteor.logout() in console), the router reactively goes to the login page.

This doesn't seem to work in Flow Router. As far as I can tell, the middlewares aren't called when logging out. What is the correct way to do this in FR?

Cheers.

Best way to check permissions

I'm finishing to spend my application from Iron-router to Flow-layout and am very happy with the result. the only thing I'm missing now is to check the permissions of a user and see if he can enter the route

on iron router I was doing something like this

Router.onBeforeAction(function () {
  var user = Meteor.user();
  // check
});

and flow-router would be something like this

FlowRouter.middleware(function () {
  Tracker.autorun(function () {
    if (FlowRouter.subsReady()) {
      var user = Meteor.user();
      // check
    }
  })
});

I'm not sure if this is the right way to use flow-router so I would ask if there is a better way

Hooks

As there are no hooks available, is there a way to replicate this behavior below?

Router.onStop(function () {
  IonScrollPositions[Router.current().route.getName()] = $('.overflow-scroll').scrollTop();
});

I mean, is there an easy way to run some sort of code right before a route change? Middlewares aren't able to do that because it runs only at the initialization step and it's already lost previous route access.

Thanks

Correct way of doing that

Okay, I would like to switch iron router, but I have to make sure I understand everything correct and ask some questions.

Lets take a shop example with admin part.
The basic admin layout is:

sidebar | main-contents

All admin parts must check for a logged in user and his permissions. I should probably use middleware for the check.

_1. How can I check all admin routes with this middleware function ? I can specify this in each route, but if there are 100 routes, this is not so cool. I can do a global middleware, but I want this only for admin part, not the whole website. What is the solution?

_2. In the sidebar there is orders counter, so it is shared across all the admin routes. As far as I understand, route subscriptions are re-run on route check. I want the global orders subscription for all admin routes. Global subscription is again for the whole website. I can use template helpers, but.. the router aims to do that kind of stuff, yes? What is the solution?

Next part is the orders page. I want to use flow layout. The layout is like the admin one, but with an upgrade.

sidebar | orders-list | selected order

_3. Can I nest the admin layout, insert in the main-contents part the template with 2 dynamic parts and then insert this two parts. Smth like:

FlowLayout.render('admin-layout', { 
    sidebar: "admin-sidebar", main-contents: "admin-two-sections",
    // This is the admin-two-sections 2 dynamic parts
    left-section: "admin-orders-list", right-part: "admin-selected-order"
});

Or should I create a new admin-orders layout and duplicate sidebar there ?

_4. As we can see, I use the same sidebar everywhere and have to specify this in every route. With default Meteor behaviour I can make an admin-layout and insert the sidebar template there. {{> admin-sidebar}}. Is this the preferred way to do with the flow layout?

_5. The three routes:
/admin/orders, /admin/orders/:id, /admin/orders/:id/edit use the sidebar and orders-list, so that the only selected order part is changed. Again, I have to copy-paste this in every route. The orders-list shares the global admin subscription and should not re-run on route changes. What is the solution ?

_6. I want named routes, for example /admin/orders named as admin.orders.index and /admin/orders/:id as admin.orders.show. Plus, I want a template helper to insert the path for me.
<a href="helperName 'admin.orders.show' id">{{title}}</a>. This is not included, am I right?

So, all in all, what is the way to nest routes, templates and share subscriptions? Some kind of controllers or route groups stuff, where I can nest the layout, subscriptions, middleware stuff and only add the needed ones?

Difference with IronRouter?

The README should mention differences/benefits to iron-router. Why should I use flow router to begin with? It is because of the flow-components architecture? is it just because it lightweight.

typo in REDME

At the end of Router Definition: (We'll talk about this is a moment).

how to get the custom property in router?

I would like to set page header on router property like this:

FlowRouter.route('/blog/:postId', {
    pageHeader: {title: 'My Title', icon: 'home'},
    .........................................
});

how to get the custom property?
because i would like to generate page header, breadcrumbs...

From Iron to Flow Guide

Is there a good strategy on migrating a page using iron:router to flow router? I'm just having problems with the new iron:router and flow router seems really predictable. I have to admit that I've just looked ad flow router for the first time and it might be so easy, that you don't need a guide or good advise for migrating it, but it might be a question other people have as well. So maybe a small migration guide or a comment in the docs might be helpful!

Route names instead of URLs, and alternatives to iron routers linkFor/urlFor.

Is there a way to create links like with iron routers linkFor / urlFor ?

Also wouldn't it be better to give each route a name so we create links using the name rather than the URL?

Rather than using a url like:

Router.go('/posts');

Use names:

Router.go('postsList');

Creating the route might look something like this:

FlowRouter.route('postsList', '/posts', {
    action: function() {

    }
});

Using names means that if we decide to use a different URL for that route we don't have to change it throughout the application as well.

Simplify even more?

Having used Iron Router in the past 12 months, I dreamed about a simpler client-only router package. Here it is, thanks a lot!

In my dream, the new router was decoupled from template rendering. You did it!

In my dream, the new router was decoupled from subscription management. Is there a reason you didn't go this far? What would be the difference between:

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

and:

FlowRouter.route('/blog/:postId', {
    action: function(params, queryParams) {
        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
        ...
    }
});

and finally:

FlowRouter.route('/blog/:postId', {});
Tracker.autorun(function() {
    Meteor.subscribe('blogPost', FlowRouter.getParam('postId'));
});

?

In my dream, the new router would even have no action function. Why not just have the following?:

FlowRouter.route('/blog/:postId');
Tracker.autorun(function() {
    // Use the FlowRouter API the way I want
    ...
});

Current path

Hello,

I have a menu in my app and I want to highlight the current link in it. The FlowRouter.current() isn't reactive and you're discouraging the use of FlowRouter.currentReactive(). I'm wondering what's the correct way of implementing this "feature" with FlowRouter?

FlowRouter.current().path doesnt return current path

for a path defined like this

FlowRouter.route("/apps/:appId/:section/:subSection", {
...
});

FlowRouter.current().path gives "/apps/:appId/:section/:subSection" not something like "/apps/PDsnZug5d5TsZTLqs/dashboard/overview"

data flow and offline data

So I am working on an app that will use GroundDB. I would like to use flow-router in that app but I am having a hard time building the data flow.
Here is what I mean:

//lets assume this route
FlowRouter.route('/myPost/:postId', {
  subscriptions: function(params, queryParams) {
        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
    },
   action: function(params, queryParams) {
        console.log("Params:", params);
        console.log("Query Params:", queryParams);
    }
});

The above is great for online apps where you are only sending down the data that you need. But with all the data, much more then you need, already existing on the client, because they are offline, this does not work as well.

How would I tell my templates which post we want to look at? I could use Sessions but I want to get away from always using globals. I could use FlowRouter.getParam(paramName); but seems like a very bad idea and I doubt it will lead to DRY code. I am considering using FlowLayout and likely normal Blaze.

How does "safeToRun" works?

I call Session.get inside my .subscriptions route. It works without any error and I didn't notice any change.

By reading source code, I think it's purpose to avoid using reactive data in .subscriptions.

Handling "no data" scenario

Hello,

I'm wondering how to handle the "no data" scenario with the FlowRouter. Let's say I want to have a route /article/:slug on which I want to render an Article (fetched by the slug field) along with related comments (separate collection). So I'll define a route like this:

FlowRouter.route('/article/:slug', {
  subscriptions: function(params) {
    this.register('article', Meteor.subscribe('articleSlug', params.slug));
    this.register('comments', Meteor.subscribe('commentsByArticleSlug', params.slug));
  },
  action: function() {
    FlowLayout.render('appLayout', { main: "articleDetail" });
  }
});

In the template I'll display the article details & comments when when subs are ready, until then just "loading..." text.

But what if the :slug param in the URL doesn't match any article in the DB? I don't want to keep displaying the "loading..." text, I want to display some sort of "Article not found" message. How to do this?

Thanks for any advice.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.