forked from prerender/prerender-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
264 lines (221 loc) · 6.98 KB
/
index.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
var request = require('request')
, url = require('url')
, zlib = require('zlib');
var prerender = module.exports = function(req, res, next) {
if(!prerender.shouldShowPrerenderedPage(req)) return next();
prerender.beforeRenderFn(req, function(err, cachedRender) {
if (!err && cachedRender) {
if (typeof cachedRender == 'string') {
res.writeHead(200, {
"Content-Type": "text/html"
});
return res.end(cachedRender);
} else if (typeof cachedRender == 'object') {
res.writeHead(cachedRender.status || 200, {
"Content-Type": "text/html"
});
return res.end(cachedRender.body || '');
}
}
prerender.getPrerenderedPageResponse(req, function(err, prerenderedResponse){
prerender.afterRenderFn(err, req, prerenderedResponse);
if(prerenderedResponse){
res.writeHead(prerenderedResponse.statusCode, prerenderedResponse.headers);
return res.end(prerenderedResponse.body);
} else {
next(err);
}
});
});
};
// googlebot, yahoo, and bingbot are not in this list because
// we support _escaped_fragment_ and want to ensure people aren't
// penalized for cloaking.
prerender.crawlerUserAgents = [
// 'googlebot',
// 'yahoo',
// 'bingbot',
'baiduspider',
'facebookexternalhit',
'twitterbot',
'rogerbot',
'linkedinbot',
'embedly',
'quora link preview',
'showyoubot',
'outbrain',
'pinterest/0.',
'developers.google.com/+/web/snippet',
'slackbot',
'vkShare',
'W3C_Validator',
'redditbot',
'Applebot',
'WhatsApp',
'flipboard'
];
prerender.extensionsToIgnore = [
'.js',
'.css',
'.xml',
'.less',
'.png',
'.jpg',
'.jpeg',
'.gif',
'.pdf',
'.doc',
'.txt',
'.ico',
'.rss',
'.zip',
'.mp3',
'.rar',
'.exe',
'.wmv',
'.doc',
'.avi',
'.ppt',
'.mpg',
'.mpeg',
'.tif',
'.wav',
'.mov',
'.psd',
'.ai',
'.xls',
'.mp4',
'.m4a',
'.swf',
'.dat',
'.dmg',
'.iso',
'.flv',
'.m4v',
'.torrent',
'.woff',
'.ttf',
'.svg'
];
prerender.whitelisted = function(whitelist) {
prerender.whitelist = typeof whitelist === 'string' ? [whitelist] : whitelist;
return this;
};
prerender.blacklisted = function(blacklist) {
prerender.blacklist = typeof blacklist === 'string' ? [blacklist] : blacklist;
return this;
};
prerender.shouldShowPrerenderedPage = function(req) {
var userAgent = req.headers['user-agent']
, bufferAgent = req.headers['x-bufferbot']
, isRequestingPrerenderedPage = false;
if(!userAgent) return false;
if(req.method != 'GET' && req.method != 'HEAD') return false;
//if it contains _escaped_fragment_, show prerendered page
var parsedQuery = url.parse(req.url, true).query;
if(parsedQuery && parsedQuery['_escaped_fragment_'] !== undefined) isRequestingPrerenderedPage = true;
//if it is a bot...show prerendered page
if(prerender.crawlerUserAgents.some(function(crawlerUserAgent){ return userAgent.toLowerCase().indexOf(crawlerUserAgent.toLowerCase()) !== -1;})) isRequestingPrerenderedPage = true;
//if it is BufferBot...show prerendered page
if(bufferAgent) isRequestingPrerenderedPage = true;
//if it is a bot and is requesting a resource...dont prerender
if(prerender.extensionsToIgnore.some(function(extension){return req.url.indexOf(extension) !== -1;})) return false;
//if it is a bot and not requesting a resource and is not whitelisted...dont prerender
if(Array.isArray(this.whitelist) && this.whitelist.every(function(whitelisted){return (new RegExp(whitelisted)).test(req.url) === false;})) return false;
//if it is a bot and not requesting a resource and is not blacklisted(url or referer)...dont prerender
if(Array.isArray(this.blacklist) && this.blacklist.some(function(blacklisted){
var blacklistedUrl = false
, blacklistedReferer = false
, regex = new RegExp(blacklisted);
blacklistedUrl = regex.test(req.url) === true;
if(req.headers['referer']) blacklistedReferer = regex.test(req.headers['referer']) === true;
return blacklistedUrl || blacklistedReferer;
})) return false;
return isRequestingPrerenderedPage;
};
prerender.getPrerenderedPageResponse = function(req, callback) {
var options = {
uri: url.parse(prerender.buildApiUrl(req)),
followRedirect: false,
headers: {}
};
if (this.forwardHeaders === true) {
Object.keys(req.headers).forEach(function(h) {
options.headers[h] = req.headers[h];
});
}
options.headers['User-Agent'] = req.headers['user-agent'];
options.headers['Accept-Encoding'] = 'gzip';
if(this.prerenderToken || process.env.PRERENDER_TOKEN) {
options.headers['X-Prerender-Token'] = this.prerenderToken || process.env.PRERENDER_TOKEN;
}
request.get(options).on('response', function(response) {
if(response.headers['content-encoding'] && response.headers['content-encoding'] === 'gzip') {
prerender.gunzipResponse(response, callback);
} else {
prerender.plainResponse(response, callback);
}
}).on('error', function(err) {
callback(err);
});
};
prerender.gunzipResponse = function(response, callback) {
var gunzip = zlib.createGunzip()
, content = '';
gunzip.on('data', function(chunk) {
content += chunk;
});
gunzip.on('end', function() {
response.body = content;
delete response.headers['content-encoding'];
delete response.headers['content-length'];
callback(null, response);
});
gunzip.on('error', function(err){
callback(err);
});
response.pipe(gunzip);
};
prerender.plainResponse = function(response, callback) {
var content = '';
response.on('data', function(chunk) {
content += chunk;
});
response.on('end', function() {
response.body = content;
callback(null, response);
});
};
prerender.buildApiUrl = function(req) {
var prerenderUrl = prerender.getPrerenderServiceUrl();
var forwardSlash = prerenderUrl.indexOf('/', prerenderUrl.length - 1) !== -1 ? '' : '/';
var protocol = req.connection.encrypted ? "https" : "http";
if (req.headers['cf-visitor']) {
var match = req.headers['cf-visitor'].match(/"scheme":"(http|https)"/);
if (match) protocol = match[1];
}
if (req.headers['x-forwarded-proto']) {
protocol = req.headers['x-forwarded-proto'].split(',')[0];
}
if (this.protocol) {
protocol = this.protocol;
}
// var fullUrl = protocol + "://" + (this.host || req.headers['host']) + req.url;
var fullUrl = "https://" + (this.host || req.headers['host']) + req.url; //modified to force https
return prerenderUrl + forwardSlash + fullUrl;
};
prerender.getPrerenderServiceUrl = function() {
return this.prerenderServiceUrl || process.env.PRERENDER_SERVICE_URL || 'http://service.prerender.io/';
};
prerender.beforeRenderFn = function(req, done) {
if (!this.beforeRender) return done();
return this.beforeRender(req, done);
};
prerender.afterRenderFn = function(err, req, prerender_res) {
if (!this.afterRender) return;
this.afterRender(err, req, prerender_res);
};
prerender.set = function(name, value) {
this[name] = value;
return this;
};