|
| 1 | +const express = require('express') |
| 2 | +const next = require('next') |
| 3 | +const LRUCache = require('lru-cache') |
| 4 | + |
| 5 | +const app = next({ dir: '.', dev: true }) |
| 6 | +const handle = app.getRequestHandler() |
| 7 | + |
| 8 | +// This is where we cache our rendered HTML pages |
| 9 | +const ssrCache = new LRUCache({ |
| 10 | + max: 100, |
| 11 | + maxAge: 1000 * 60 * 60 // 1hour |
| 12 | +}) |
| 13 | + |
| 14 | +app.prepare() |
| 15 | +.then(() => { |
| 16 | + const server = express() |
| 17 | + |
| 18 | + // Use the `renderAndCache` utility defined below to serve pages |
| 19 | + server.get('/', (req, res) => { |
| 20 | + renderAndCache(req, res, '/') |
| 21 | + }) |
| 22 | + |
| 23 | + server.get('/blog/:id', (req, res) => { |
| 24 | + const queryParams = { id: req.paradms.id } |
| 25 | + renderAndCache(req, res, '/blog', queryParams) |
| 26 | + }) |
| 27 | + |
| 28 | + server.get('*', (req, res) => { |
| 29 | + return handle(req, res) |
| 30 | + }) |
| 31 | + |
| 32 | + server.listen(3000, (err) => { |
| 33 | + if (err) throw err |
| 34 | + console.log('> Ready on http://localhost:3000') |
| 35 | + }) |
| 36 | +}) |
| 37 | + |
| 38 | +function renderAndCache (req, res, pagePath, queryParams) { |
| 39 | + // If we have a page in the cache, let's serve it |
| 40 | + if (ssrCache.has(req.url)) { |
| 41 | + console.log(`CACHE HIT: ${req.url}`) |
| 42 | + res.send(ssrCache.get(req.url)) |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + // If not let's render the page into HTML |
| 47 | + app.renderToHTML(req, res, pagePath, queryParams) |
| 48 | + .then((html) => { |
| 49 | + // Let's cache this page |
| 50 | + console.log(`CACHE MISS: ${req.url}`) |
| 51 | + ssrCache.set(req.url, html) |
| 52 | + |
| 53 | + res.send(html) |
| 54 | + }) |
| 55 | + .catch((err) => { |
| 56 | + app.renderError(err, req, res, pagePath, queryParams) |
| 57 | + }) |
| 58 | +} |
0 commit comments