Server side caching with express and possibly middleware

369 views
Skip to first unread message

chri...@stxclock.com

unread,
May 20, 2017, 8:47:34 AM5/20/17
to Express
Hi,

I'm new to express, so I don't even know if this is possible. I have an Angular app where the content is mainly built up from a http response from a third party (that I also made) in the form of a json. This is the content that I want google to be able to index and view as "structured data". However, Googlebot doesn't see any of the data that comes from the https request (though the user does). The app uses express for serving the app. The json changes very infrequently (in time it will be monthly).

I belive the reason is that the result from the http request is the last thing that arrives on the page.

I was thinking that the solution would be to either cache the json with express so that it arrives together with the rest of the page, or to cache the entire "/" (which is the only domain that uses the data) including the prerendered data. 

I've been looking into both Route-Cache and ApiCache, but that doesn't seem to do the trick. Here is my server.ts trying to use Route-Cache:
import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

import { ROUTES } from './routes';
const PORT = process.env.PORT || 4000;


enableProdMode();

const app = express();
const cache = require('route-cache');
const compression = require('compression');

app.use(compression());

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
 const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
   .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.use('/', express.static('dist', {index: false}));

ROUTES.forEach(route => {
 app.get(route, cache.cacheSeconds(60), function(req, res) {
   console.time(`GET: ${req.originalUrl}`);
   console.log('you will only see this every 60 seconds');
   res.render('../dist/index', {
     req: req,
     res: res
   });
   console.timeEnd(`GET: ${req.originalUrl}`);
 });
});

app.listen(PORT, () => {
 console.log(`listening on http://localhost:${PORT}!`);
});


Does anyone have any ideas for what I should do?
Reply all
Reply to author
Forward
0 new messages