Last active
March 7, 2021 10:02
-
-
Save akellbl4/5c6ff2c4926e8bdb20f3f6942793a8fa to your computer and use it in GitHub Desktop.
Article: https://itnext.io/fetch-shared-data-in-next-js-with-single-request-833433fa8ed1 Full code: https://github.com/akellbl4/cache-proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require("http"); | |
const fetch = require("isomorphic-unfetch"); | |
const { API_URL, PORT, HOST } = process.env; | |
const map = new Map(); | |
async function handler(req, res) { | |
if (map.has(req.url)) { | |
const data = await map.get(req.url); | |
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }); | |
res.write(data); | |
res.end(); | |
console.log(`📦 Cached request to: ${req.url}`); | |
return; | |
} | |
const request = fetch(`${API_URL}${req.url}`).then((res) => res.text()); | |
map.set(req.url, request); | |
const data = await request; | |
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }); | |
res.write(data); | |
res.end(); | |
console.log(`📥 GET ${req.url}`); | |
} | |
http.createServer(handler).listen(PORT, HOST, () => { | |
console.log(`Server is running on 🌎 http://${HOST}:${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment