generated from sanishkr/next-tailwind-styled-components
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
54 lines (49 loc) · 1.71 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const express = require('express');
const { join } = require('path');
const { parse } = require('url');
const compression = require('compression');
const next = require('next');
// const Cookies = require("universal-cookie");
const routes = require('./routes');
const port = process.env.PORT || 3000;
const app = next({ dev: process.env.NODE_ENV !== 'production' });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
// Serve as GZIP
server.use(compression());
server.get('/service-worker.js', (req, res) => {
// const filePath = path.resolve('service-worker.js');
const parsedUrl = parse(req.url, true);
const { pathname } = parsedUrl;
const filePath = join(__dirname, '.next/static/', pathname);
res.setHeader(
'Cache-Control',
'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
);
// adding no-caching for service worker
// Don't cache service worker is a best practice
// Clients wont get emergency bug fixes etc.
res.set('Content-Type', 'application/javascript');
// res.setHeader('Clear-Site-Data', 'cookies, cache'); // adding kill-switch during new deployment, if you want
app.serveStatic(req, res, filePath);
});
const handler = routes.getRequestHandler(
app,
({ req, res, route, query }) => {
app.render(req, res, route.page, query);
},
);
server.use(handler);
server.get('*', (req, res) => handle(req, res));
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch(err => {
console.error(err.stack);
process.exit(1);
});