Skip to content

Instantly share code, notes, and snippets.

@alberteddu
Created January 15, 2021 10:39
Show Gist options
  • Save alberteddu/a6222fe76666c9d42d3391d9255ffe64 to your computer and use it in GitHub Desktop.
Save alberteddu/a6222fe76666c9d42d3391d9255ffe64 to your computer and use it in GitHub Desktop.
Server and copy attachments
// util/copy-attachments.js
// This is supposed to copy all files to the url where next.js expects them as a static file.
// The example I have is too tailored to my library to make any sense to anyone else.
// However, the theory is: static file is expected at /some/url/hey.png
// When running next.js in dev, server.js will serve this url instead, because this file is not in
// the public folder, but is instead in the content folder I manage.
// When building, I run this script (see package.json example below) which will move hey.png
// to public/some/url/hey.png.
{
"scripts": {
"dev": "node util/server.js",
"build": "yarn copy-attachments && next build",
"start": "next start",
"export": "next export",
"copy-attachments": "node util/copy-attachments.js"
},
"...": {}
}
// util/server.js
const express = require('express');
const next = require('next');
const { Node } = require('@lbrto/prim'); // this is my library which handles page/attachment resolution
const prim = require('./content');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.all('*', (req, res) => {
// at this point I am using my library, but anything works here.
// As soon as you realise you need to serve a static file,
// use sendFile as in the line 20
const node = prim.get(req.url);
if (node && Node.isAttachment(node)) {
res.sendFile(node.getPath().getPath());
return;
}
// If not a static file, just let next.js do the rest
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment