Session data becomes null after navigation in multi-page apps using Meteor and Backbone

Greetings everyone! I am currently developing a web application using meteorjs. Thanks to backbone, I have successfully implemented a multipage feature in my web app. Take a look at my router.js code below:

Router = {
    uri: _.compact(window.location.pathname.split("/")),
    routes: [],

    addRoute: function(route, template, session, currTemplateType) {
        var segments =  _.compact(route.split("/"));

        var placeholders = _.reduce(segments, function(currentArr, piece, index) {
            if (piece.substr(0, 1) === ":") {
                currentArr.push(index);
                segments[index] = piece.substr(1);
            }
            return currentArr;
        }, []);

        this.routes.push({
            segments: segments,
            template: template,
            placeholderIndexes: placeholders,
            session : session,
            currTemplateType : currTemplateType
        });
    },
    getMatchingRoute: function(){
        for (var i in this.routes) {
            var route = this.routes[i];
            var data = {};

            if (route.segments.length === this.uri.length) {
                var match = _.every(route.segments, function(seg, i){
                    if (_.contains(route.placeholderIndexes, i)) {
                        data[seg] = this.uri[i];
                        return true;
                    } else {
                        return seg === this.uri[i];
                    }
                }, this);

                if (match) {
                    return {
                        data: data,
                        template: route.template,
                        session: route.session,
                        currTemplateType: route.currTemplateType
                    }
                }
            }
        }
        //no matches (add 404 or default template maybe?)
        return false;
    },
    run: function(){
        var route = this.getMatchingRoute();
        if (route) {
            var fragment = Meteor.render(function() {
                if (Template[route.template] !== undefined) {
                    return Template[route.template](route.data);
                }
            });
            Session.set(SessionLookUp.pageByURL, route.session);
            Session.set(SessionLookUp.currentTemplateType, route.currTemplateType);
            if(route.currTemplateType !== TemplateType.login){
                var isLog =  "true";
                if(isLog === undefined || isLog === "false")
                    window.location.href = "/cust/login";
                else{
                    document.body.appendChild(fragment);
                }
            }
            else{
                document.body.appendChild(fragment);
            }
        } else {

            var fragment = Meteor.render(function() {
                    return Template["404_page"](route.data);
            });

            document.body.appendChild(fragment);
        }
    }
};

And here are some snippets from my pager.js:

Router.addRoute('/cust/login', 'login', UserType.customer, TemplateType.login);
    Router.addRoute('/cust/register','cust_reg', UserType.customer, TemplateType.register);
    Router.addRoute('/cust/profile', 'cust_profile', UserType.customer,"");

In my scenario, when a user logs in at localhost:3000/cust/login and the username and password are verified, the system will redirect them to localhost:3000/cust/profile. You can see how I navigate the page in the code snippet below:

Session.set(SessionLookUp.isLoggedIn, "true");
window.location.href = "/cust/profile";

However, there seems to be an issue where the session becomes null or undefined after the above code executes. Can anyone shed some light on why this is happening and provide a solution? I suspect the problem may lie in how I handle the page redirection. By the way, I've created a custom login form.

Answer №1

Within the meteor community, iron-router is widely chosen as the go-to router for app development due to its tailored design specifically for meteor. Consequently, finding meteor help focused on backbone may prove challenging. While not an expert in backbone, I will attempt to address any glaring inaccuracies:

  1. Manually setting window.location will reset the current meteor connection, leading to a reset of session variables and subscriptions. It is advisable to avoid this. Instead, in iron-router, utilize Router.go to maintain proper browser state.
  2. When utilizing the native accounts packages, checking user login status can be done simply by verifying if Meteor.userId() returns a string, without the need for additional session variables.
  3. It deviates greatly from meteor principles to manually invoke document.body.appendChild. Refer to iron-router examples for guidance on how to effectively use templates with routes.

For further insight into the cohesion of these concepts, consider delving into the meteor book. Even if you opt to retain your current router, I hope this information proves beneficial in some way.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the source of the currently displayed image within a carousel of images

Looking to retrieve the src of the active image in a carousel of images. Currently, my code is as follows: $(document).ready(function () { $("#myCarousel1").on('slide.bs.carousel', function () { var ele = $('.carousel ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

Is it typical to experience a forced reflow violation and page offset?

After implementing a position: fixed on-scroll feature for my navbar, I noticed an error being thrown by the DOM stating: [Violation] Forced reflow while executing JavaScript took ms during every scroll event. It seems that this could be caused by layout t ...

Vue Websockets twofold

I am experiencing some issues with Laravel/Echo websockets and Vue.js integration. I have set up everything as required, and it works, but not quite as expected. The problem arises when I refresh the page and send a request - it displays fine. However, if ...

Looking to automatically populate input fields using AJAX?

Need help auto filling input bars with AJAX, encountering a small issue Below is the HTML code: <input type="text" name="url" id="url"> <input type="text" name="name" id="name"> <input type="text" name="catagory" id="catagory> When t ...

Jest is unable to utilize Higher Order Components from JavaScript files, but it functions properly with Higher Order Components from TypeScript files

When I try to import an HOC from a tsx file, everything works fine. However, when I change the extension to js, Jest throws an error: Jest encountered an unexpected token. This usually indicates that you are attempting to import a file that Jest is unabl ...

Execute a script to display an alert and redirect on Internet Explorer before an error occurs in Gatsby

I am currently operating a Gatsby site through Netlify, and I have encountered a specific error or crash that is only affecting Internet Explorer. In order to address this issue, I want to display an alert to users on IE and then redirect them to the Chrom ...

Showcase Pictures from a Document

Is there a way to upload an image via an input field and display it? I want to showcase a profile picture that can be saved in a database. The process should be simple for the user, with the ability to easily upload and view the image. function Save() { ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

org.openqa.selenium.UnexpectedAlertOpenException: error occurred due to an unanticipated alert opening

While using the Chrome Driver to test a webpage, I typically have no issues. However, there are times when exceptions occur: org.openqa.selenium.UnhandledAlertException: unexpected alert open (Session info: chrome=38.0.2125.111) (Driver info: chromedri ...

React - Insert a Component in-between two already rendered components

As a React beginner, I am working on creating a dynamic form that allows users to add and remove fields. However, I encountered an issue with rendering after adding a new row (field). Below is my Row Component, which serves as a template filled with props ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

Smartlook fails to correctly store user consent

I am currently working on integrating Smartlook into our website. Since we are using React, I am unable to follow the suggested steps in the documentation which can be found here. Our implementation involves initializing Smartlook using a script tag in th ...

Angular 4 showcases the information stored within this dataset

The data returned from an API to my Angular 4 application is not to my liking. Here is an example of the JSON, where I am only interested in the coin and its price: Goal is to display this data on the page: Coin Price BTC $4,281.28 ETH $294.62 ...

Is it necessary to implement a restful API for all database interactions in my Node.js application?

Currently, I am in the process of developing a simple blogging platform utilizing mongoose, node, express, Jade, and bootstrap. As I tackle the task of loading post content, I find myself contemplating whether to conduct database operations directly within ...

Discovering the maximum value and fetching it from an array

Can you help me identify the array element with the highest 'conversion' value? var barTextData = [ { term: "Roof", clicks: 11235, conversion: 3.12 }, { term: "Snow", clicks: 6309, conversion: 4.45 }, { term: "Chains" ...

Enhance Page Content Dynamically with Symfony2 and Ajax-Like Functionality

When assessing an ArrayCollection in my Template, I am currently using the following loop: {% for article in articles %} <li {% if article.new %} class="new" {% endif %} >{{ article.name|e }}</li> {% endfor %} My go ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

An innovative concept of housing two distinct retailers under one app

I am facing an issue with my vue.js application that consists of a landing page, user dashboard, and admin dashboard. Each section has different states, but they all share a common shared module with important data like page width, token, current user, etc ...

Storing an array in $cacheFactory with AngularJS

Having some trouble saving an array in AngularJS' $cacheFactory. When attempting to retrieve the array, it's coming back as undefined. Here is the code snippet: angular.module('cacheExampleApp', []). controller('CacheContro ...