Skip to content

Commit

Permalink
[examples] Fix for custom server SSR caching (#18786)
Browse files Browse the repository at this point in the history
  • Loading branch information
sphilee committed Feb 7, 2021
1 parent 1773b99 commit fb843a5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
8 changes: 4 additions & 4 deletions examples/ssr-caching/package.json
Expand Up @@ -7,12 +7,12 @@
"start": "cross-env NODE_ENV=production node server.js"
},
"dependencies": {
"cacheable-response": "^1.1.0",
"cacheable-response": "^2.1.6",
"cross-env": "^7.0.2",
"express": "^4.14.0",
"express": "^4.17.1",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0"
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"license": "MIT"
}
25 changes: 11 additions & 14 deletions examples/ssr-caching/server.js
Expand Up @@ -11,18 +11,17 @@ const handle = app.getRequestHandler()
const ssrCache = cacheableResponse({
ttl: 1000 * 60 * 60, // 1hour
get: async ({ req, res }) => {
const data = await app.render(req, res, req.path, {
...req.query,
...req.params,
const rawResEnd = res.end
const data = await new Promise((resolve) => {
res.end = (payload) => {
resolve(res.statusCode === 200 && payload)
}
app.render(req, res, req.path, {
...req.query,
...req.params,
})
})

// Add here custom logic for when you do not want to cache the page, for
// example when the page returns a 404 status code:
if (res.statusCode === 404) {
res.end(data)
return
}

res.end = rawResEnd
return { data }
},
send: ({ data, res }) => res.send(data),
Expand All @@ -33,9 +32,7 @@ app.prepare().then(() => {

server.get('/', (req, res) => ssrCache({ req, res }))

server.get('/blog/:id', (req, res) => {
return ssrCache({ req, res })
})
server.get('/blog/:id', (req, res) => ssrCache({ req, res }))

server.get('*', (req, res) => handle(req, res))

Expand Down

0 comments on commit fb843a5

Please sign in to comment.