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:
parent
f9b52cfcb6
commit
2473b55871
|
@ -45,26 +45,32 @@ function getCacheKey (req) {
|
||||||
return `${req.url}`
|
return `${req.url}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderAndCache (req, res, pagePath, queryParams) {
|
async function renderAndCache (req, res, pagePath, queryParams) {
|
||||||
const key = getCacheKey(req)
|
const key = getCacheKey(req)
|
||||||
|
|
||||||
// If we have a page in the cache, let's serve it
|
// If we have a page in the cache, let's serve it
|
||||||
if (ssrCache.has(key)) {
|
if (ssrCache.has(key)) {
|
||||||
console.log(`CACHE HIT: ${key}`)
|
res.setHeader('x-cache', 'HIT')
|
||||||
res.send(ssrCache.get(key))
|
res.send(ssrCache.get(key))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// If not let's render the page into HTML
|
try {
|
||||||
app.renderToHTML(req, res, pagePath, queryParams)
|
// If not let's render the page into HTML
|
||||||
.then((html) => {
|
const html = await app.renderToHTML(req, res, pagePath, queryParams)
|
||||||
// Let's cache this page
|
|
||||||
console.log(`CACHE MISS: ${key}`)
|
|
||||||
ssrCache.set(key, html)
|
|
||||||
|
|
||||||
|
// Something is wrong with the request, let's skip the cache
|
||||||
|
if (res.statusCode !== 200) {
|
||||||
res.send(html)
|
res.send(html)
|
||||||
})
|
return
|
||||||
.catch((err) => {
|
}
|
||||||
app.renderError(err, req, res, pagePath, queryParams)
|
|
||||||
})
|
// 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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue