Commit 3998805b authored by Kiko Beats's avatar Kiko Beats Committed by Tim Neutkens

Use cacheable-response for ssr (#6393)

Hello,

I have been using next.js for a while in a bunch of projects, so first for all thanks for all the vibrant effort around the project 🖤. 

Always I see the server side next.js approach as an advantage, but also a weakness for the extra resources you need to have, specially comparing how cheap is a client side app.

In order to do my things cheaper, I started using the SSR pattern you suggested in your examples, so useful! It saves time and resources.

However, it was *too simple*. In a real production scenario, you need a bit more, specially related with send the right response headers to keep the rest of external network agent updated of your cache state.

I started a tiny script code for doing that; basically, I copy/paste it on my ssr projects.

Now, after a time, I think it's worth it publish it as [cacheable-response](https://github.com/Kikobeats/cacheable-response) module.

The PR is for adding the module leverage into the next.js ssr example. 

It's doing the same, plus:

- be possible use a multi storage cache (memory by default; mongodb, redis, mysql, supported).
- sending `cache-control` response headers.
- sending `X-Cache-Expired-At`, just a humanize way to see the expiration time.
- support for forcing invalidation via `force=true` query parameter.

I hope you like it 🙂
parent aed7f643
......@@ -7,11 +7,11 @@
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"cacheable-response": "^1.1.0",
"express": "^4.14.0",
"lru-cache": "^4.0.2",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0"
},
"license": "ISC"
}
}
\ No newline at end of file
const cacheableResponse = require('cacheable-response')
const express = require('express')
const next = require('next')
const LRUCache = require('lru-cache')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
length: function (n, key) {
return n.toString().length + key.toString().length
},
max: 100 * 1000 * 1000, // 100MB cache soft limit
maxAge: 1000 * 60 * 60 // 1hour
const ssrCache = cacheableResponse({
ttl: 1000 * 60 * 60, // 1hour
get: async ({ req, res, pagePath, queryParams }) => ({
data: await app.renderToHTML(req, res, pagePath, queryParams)
}),
send: ({ data, res }) => res.send(data)
})
app.prepare().then(() => {
const server = express()
// Use the `renderAndCache` utility defined below to serve pages
server.get('/', (req, res) => {
renderAndCache(req, res, '/')
})
server.get('/', (req, res) => ssrCache({ req, res, pagePath: '/' }))
server.get('/blog/:id', (req, res) => {
const queryParams = { id: req.params.id }
renderAndCache(req, res, '/blog', queryParams)
const pagePath = '/blog'
return ssrCache({ req, res, pagePath, queryParams })
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.get('*', (req, res) => handle(req, res))
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
/*
* NB: make sure to modify this to take into account anything that should trigger
* an immediate page change (e.g a locale stored in req.session)
*/
function getCacheKey (req) {
return `${req.url}`
}
async function renderAndCache (req, res, pagePath, queryParams) {
const key = getCacheKey(req)
// If we have a page in the cache, let's serve it
if (ssrCache.has(key)) {
res.setHeader('x-cache', 'HIT')
res.send(ssrCache.get(key))
return
}
try {
// If not let's render the page into HTML
const html = await app.renderToHTML(req, res, pagePath, queryParams)
// Something is wrong with the request, let's skip the cache
if (res.statusCode !== 200) {
res.send(html)
return
}
// Let's cache this page
ssrCache.set(key, html)
res.setHeader('x-cache', 'MISS')
res.send(html)
} catch (err) {
app.renderError(err, req, res, pagePath, queryParams)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment