From 54622b54bb0056bf6c2b95409b329ff83c5ffbc8 Mon Sep 17 00:00:00 2001 From: Avris Date: Sat, 26 Jun 2021 00:51:43 +0200 Subject: [PATCH] [optim] dynamically disable ssr for browsers --- nuxt.config.js | 2 +- server/no-ssr.js | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 server/no-ssr.js diff --git a/nuxt.config.js b/nuxt.config.js index 73bd4acd..9f8290e3 100644 --- a/nuxt.config.js +++ b/nuxt.config.js @@ -155,7 +155,7 @@ export default { BUCKET: `https://${process.env.AWS_S3_BUCKET}.s3-${process.env.AWS_REGION}.amazonaws.com`, STATS_FILE: process.env.STATS_FILE, }, - serverMiddleware: ['~/server/index.js'], + serverMiddleware: ['~/server/no-ssr.js', '~/server/index.js'], axios: { baseURL: process.env.BASE_URL + '/api', }, diff --git a/server/no-ssr.js b/server/no-ssr.js new file mode 100644 index 00000000..0f92f91c --- /dev/null +++ b/server/no-ssr.js @@ -0,0 +1,17 @@ +const USER_AGENT_BOTS = /bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google|facebookexternalhit|twitterbot|whatsapp|php|python/; +const USER_AGENT_BROWSERS = /mozilla|msie|gecko|firefox|edge|opera|safari|netscape|konqueror|android/; + +const isBrowser = (userAgent) => { + if (!userAgent) { + return false; + } + const isProbablyBot = !!userAgent.toLowerCase().match(USER_AGENT_BOTS); + const isProbablyBrowser = !!userAgent.toLowerCase().match(USER_AGENT_BROWSERS); + + return isProbablyBrowser || !isProbablyBot; +} + +export default function(req, res, next) { + res.spa = isBrowser(req.headers['user-agent']); + next() +}