3998805b2e
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 🙂
36 lines
1,009 B
JavaScript
36 lines
1,009 B
JavaScript
const cacheableResponse = require('cacheable-response')
|
|
const express = require('express')
|
|
const next = require('next')
|
|
|
|
const port = parseInt(process.env.PORT, 10) || 3000
|
|
const dev = process.env.NODE_ENV !== 'production'
|
|
const app = next({ dev })
|
|
|
|
const handle = app.getRequestHandler()
|
|
|
|
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()
|
|
|
|
server.get('/', (req, res) => ssrCache({ req, res, pagePath: '/' }))
|
|
|
|
server.get('/blog/:id', (req, res) => {
|
|
const queryParams = { id: req.params.id }
|
|
const pagePath = '/blog'
|
|
return ssrCache({ req, res, pagePath, queryParams })
|
|
})
|
|
|
|
server.get('*', (req, res) => handle(req, res))
|
|
|
|
server.listen(port, err => {
|
|
if (err) throw err
|
|
console.log(`> Ready on http://localhost:${port}`)
|
|
})
|
|
})
|