1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

[ssr-caching] Only cache 200 status requests (#3708)

* [ssr-caching] Only cache 200 requests

I'm assuming caching an error page is a bad pattern.

* Update server.js
This commit is contained in:
Olivier Tassinari 2018-02-06 13:21:49 +01:00 committed by Arunoda Susiripala
parent f9b52cfcb6
commit 2473b55871

View file

@ -45,26 +45,32 @@ function getCacheKey (req) {
return `${req.url}`
}
function renderAndCache (req, res, pagePath, queryParams) {
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)) {
console.log(`CACHE HIT: ${key}`)
res.setHeader('x-cache', 'HIT')
res.send(ssrCache.get(key))
return
}
// If not let's render the page into HTML
app.renderToHTML(req, res, pagePath, queryParams)
.then((html) => {
// Let's cache this page
console.log(`CACHE MISS: ${key}`)
ssrCache.set(key, html)
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)
})
.catch((err) => {
app.renderError(err, req, res, pagePath, queryParams)
})
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)
}
}