Meteor.subscribe("users"); // set up the main template the the router will use to build pages Router.configure({ layoutTemplate: "ApplicationLayout" }); // specify the top level route, the page users see when they arrive at the site Router.route("/", function () { console.log("rendering root /"); this.render("navbar", { to: "header" }); this.render("lobby_page", { to: "main" }); }); // specify a route that allows the current user to chat to another users Router.route("/chat/:_id", { subscriptions: function () { Meteor._debug("Subscriptions"); return Meteor.subscribe("chats"); }, action: function (req, wtf, func) { Meteor._debug("Action", req.url); if (this.ready()) { console.log("- Now ready"); // The user they want to chat to has id equal to the id sent in after /chat/... const otherUserId = this.params._id; // find a chat that has two users that match current user id // and the requested user id const filter = { $or: [ { user1Id: Meteor.userId(), user2Id: otherUserId }, { user2Id: Meteor.userId(), user1Id: otherUserId } ] }; const chat = Chats.findOne(filter); // Meteor._debug(filter, chat); // No chat matching the filter - need to insert a new one. let chatId; if (!chat) { chatId = Chats.insert({ user1Id: Meteor.userId(), user2Id: otherUserId }); console.log("--- No chat found between " + Meteor.userId() + " and " + otherUserId + ". Created " + chatId); } // There is a chat going already - use that. else { chatId = chat._id; console.log("--- Chat " + chatId + " found between " + Meteor.userId() + " and " + otherUserId + "."); } // Looking good, save the id to the session. if (chatId) { Session.set("chatId", chatId); } this.render("navbar", { to: "header" }); this.render("chat_page", { to: "main", data: function () { const other = Meteor.users.findOne({ _id: otherUserId }); console.log("--- Routing data, other: " + (other ? other.profile.username : "not available")); return { other: other }; } }); } else { console.log("- Not yet ready"); this.render("Loading"); } } });