ExpressJS Template Caching System

Encountering issues with template caching in my MEAN app. The navigation bar uses conditional logic to show/hide buttons based on user status. Upon page load, values are null or false until login (views, isLoggedIn).

The problem arises post-login - despite successful authentication and redirection using

$location.path("/pathAfterLogin");
, hidden buttons persist. Only hard refresh (Ctrl-F5) reflects correct button display based on app.js values.

Tech stack: Angular 1.5, UI-Router, Express 4, Swig templates, consolidate. NODE.ENV is set to development.

Multiple attempts made at disabling cache across the application without success.

Snippet from app.js:

'use strict';

var express = require('express'),
    path = require('path'),
    cons = require('consolidate'),
    swig = require('swig');


module.exports = function() {
    var app = express(); //start an express app app.disable('view cache');

    app.engine('html', cons.swig);

    app.set('view engine', 'html');
    app.set('views',path.join(__dirname,'../app/views'));
    app.set('view cache', false ); //set cache

    swig.setDefaults({ cache: false });

    app.get('*', stuff.test, function(req, res, next) {
        res.setHeader('Cache-Control', 'no-cache');
        res.render('index', {
            cache: false,
            views: req.views,
            isLoggedIn: req.isLoggedIn
        });
    });
        return app;
};

HTML file serves as main layout/view for this single-page application. Index.html includes a navigation file.

Included navigation file:
<div id="subtitle">
    <ul class="nav nav-pills pull-right">
        {% if !isLoggedIn %}<li ui-sref-active="active"><a ui-sref="login">Login</a></li>{% endif %}
        {% if isLoggedIn %}<li ui-sref-active="active"><a ui-sref="logout">Logout</a></li>{% endif %}
        {% for item in views %}
            {% if item == "linkA" %}<li ui-sref-active="active"><a ui-sref="linkA">LinkA</a></li>{% endif %}
            {% if item == "LinkB" %}<li ui-sref-active="active"><a ui-sref="linkB">LinkB</a></li> {% endif %}
        {% endfor %}
        {% if !isLoggedIn %}<li ui-sref-active="active"><a ui-sref="info">Info </a></li>{% endif %}
        <li class="dropdown"ui-sref-active="active">
            {% for item in views %}
                {% if resource == "mainDD" %} <a class="dropdown-toggle" data-toggle="dropdown" href="#"> Drop Downs <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                    {% for item in permissions %}
                        {% if item == "link1" %}<li><a ui-sref="link1">Link 1</a></li>{% endif %}
                        {% if item == "link2" %}<li><a ui-sref="link2">Link 2</a></li>{% endif %}
                        {% endfor %}
                    </ul>
                {% endif %}
            {% endfor %}
        </li>
    </

Inquiry:

  1. Is caching correctly disabled? If not, pinpoint issue.
  2. Is observed behavior typical for cache disablement?

Answer №1

The problem lies in the mixture of backend templating and frontend routing:

{% if isLoggedIn %}<li ui-sref-active="active"><a ui-sref="logout">Logout</a></li>{% endif %}

The isLoggedIn variable is server-side and determines whether the contents (the <li>) should be displayed in the HTML.

If the user was not logged in when the HTML was generated, only a full re-render of the template on the server side will cause the "Logout" button to show up in the served HTML.

To solve this issue, you may need to refresh the page (I am not very familiar with Angular, but $window.location.reload() might do the trick) so that the server can provide the updated HTML.

Alternatively, consider handling the logic of showing specific page elements in Angular:

<li ng-if="loggedIn" ui-sref-active="active"><a ui-sref="logout">Logout</a></li>

(where loggedIn is a variable in your controller)

Just to clarify: this issue is unrelated to caching. Express view caching does not cache rendered templates (HTML), but rather the compiled template for faster access during rendering.

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

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

The functionality of Jquery and JS lies in working on DOM elements as opposed to

Just to start off, I want to mention that my knowledge of JavaScript and specifically jQuery is quite limited. I've encountered an issue with some JavaScript and jQuery loading on my webpage. 1) I have written some code on JSFiddle http://jsfiddle.n ...

Effortlessly automate clicking with JavaScript or HTML - learn how now!

Does anyone know how to automatically click a button on a page when it loads? I attempted using this JavaScript code, but it didn't work. <a href="javascript:Clickheretoprint()" id="print"> <script type="text/javascript"> $(document).rea ...

Can someone help me understand why my component is not rendering when placed inside a conditional block, but it renders fine on its own?

I want to display a specific page only if the user is currently logged in; otherwise, prompt them to log in. My approach involves leveraging Firebase authentication for this functionality. import Head from "next/head"; import { auth } from "../../comp ...

AngularJS encounters an error when attempting to read the property 'push' of an undefined object. Surprisingly, this issue only arises upon clicking a button, as the page initially loads without any errors

angular.module('TppAdminApp.modules.dashboard.edit-project', ['angucomplete-alt', 'ngFileUpload', '720kb.datepicker']) .config(dashboardEditProjectConfig) .controller('dashboardEditProjectController&apos ...

Executing ng-click to access outer controller from within nested ng-controllers

I'm exploring the potential of using angularjs to develop a dynamic page with the following capabilities: It starts off blank, except for a dropdownlist that automatically populates with various apps. Upon selecting an app from the list, relevant da ...

Angular : How can a single item be transferred from an array list to another service using Angular services?

How to Transfer a Single List Item to the Cart? I'm working on an Angular web application and I need help with transferring a single item from one service to another service and also displaying it in a different component. While I have successfully i ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

Sorting information in the React Native Section List

Working with React Native's SectionList and filtering data: data: [ { title: "Asia", data: ["Taj Mahal", "Great Wall of China", "Petra"] }, { title: "South America", data: ["Machu Picchu", "Christ the Redeemer", "C ...

Having trouble navigating to the bottom of a VUEJS app?

I've been working on developing a chatbot app that utilizes a REST API to stream content. While the functionality of the app is running smoothly, I have encountered an issue with the scroll to bottom feature. Instead of automatically scrolling to disp ...

The ngRoute feature seems to be malfunctioning and unable to switch views when an <a> tag is clicked

Just starting out with Angular JS and encountering an issue that has me stumped. Would really appreciate some help in resolving it. In my project, I have an index file connected to app.js which utilizes ngRoute. See the code snippet below for reference: ...

Seeking out the correct method for structuring loops and callbacks within nodejs with an emphasis on asynchronous operations

I've been researching multiple posts and articles on this topic, but I'm still struggling to grasp it. In my Mongoose model, there's a piece of code dedicated to inviting people to a project. When given a list of invitees, the code checks i ...

Using VueJS to fetch and display data from a JSON file using

Currently, I am dealing with a JSON value in the following format: { "T1" : "online", "T2" : "offline" } Additionally, I have an online API which only sends me the following response: { StatusCode :"T1" } My task is to extract the code from the API res ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

The Express-session middleware in Node.js is malfunctioning in Visual Studio

Recently, I've been encountering an issue while attempting to utilize express-session within my Node.js Express application. Despite my efforts, I am unable to properly set or retrieve sessions as I keep receiving the error message "Property 'ses ...

Ensure that you do not proceed with the next step until the promise has been fulfilled

I am currently faced with a challenge in my project where I have a service that wraps a 3rd-party API to retrieve data into my controller. However, I need to perform some data processing to pivot the information before displaying it, but I am struggling to ...

Is there a way to detect duplicate usernames in a form without actually submitting the form, and then automatically focus on the username field if a duplicate is

I need help with a user registration form that I am creating. I want the form to automatically search for an existing username as soon as the user starts typing in the username field. If the username already exists, I want the field to receive focus. In my ...

Utilizing Vue and Websockets for seamless communication: Managing the exchange of messages between users

In an attempt to create a messaging system that shows alerts of messages to different users, I have implemented Vue Socket Io from https://www.npmjs.com/package/vue-socket.io. However, the issue lies in the fact that the alerts are not being triggered as e ...

Receiving a 404 error when attempting to update row values using an id with sequelize

Currently, I am working on a project using nodeJS, expressJS and reactJS. While I can access each data's id by clicking the edit button, I am facing issues with updating the data. Every time I click the button, a 404 error is displayed in the console. ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...