server.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import Vue from 'vue'
  2. import { joinURL, normalizeURL, withQuery } from 'ufo'
  3. import fetch from 'node-fetch'
  4. import middleware from './middleware.js'
  5. import {
  6. applyAsyncData,
  7. middlewareSeries,
  8. sanitizeComponent,
  9. getMatchedComponents,
  10. promisify
  11. } from './utils.js'
  12. import fetchMixin from './mixins/fetch.server'
  13. import { createApp, NuxtError } from './index.js'
  14. import NuxtLink from './components/nuxt-link.server.js' // should be included after ./index.js
  15. // Update serverPrefetch strategy
  16. Vue.config.optionMergeStrategies.serverPrefetch = Vue.config.optionMergeStrategies.created
  17. // Fetch mixin
  18. if (!Vue.__nuxt__fetch__mixin__) {
  19. Vue.mixin(fetchMixin)
  20. Vue.__nuxt__fetch__mixin__ = true
  21. }
  22. // Component: <NuxtLink>
  23. Vue.component(NuxtLink.name, NuxtLink)
  24. Vue.component('NLink', NuxtLink)
  25. if (!global.fetch) { global.fetch = fetch }
  26. const noopApp = () => new Vue({ render: h => h('div', { domProps: { id: '__nuxt' } }) })
  27. const createNext = ssrContext => (opts) => {
  28. // If static target, render on client-side
  29. ssrContext.redirected = opts
  30. if (ssrContext.target === 'static' || !ssrContext.res) {
  31. ssrContext.nuxt.serverRendered = false
  32. return
  33. }
  34. let fullPath = withQuery(opts.path, opts.query)
  35. const $config = ssrContext.runtimeConfig || {}
  36. const routerBase = ($config._app && $config._app.basePath) || '/plugins/shop_server/'
  37. if (!fullPath.startsWith('http') && (routerBase !== '/' && !fullPath.startsWith(routerBase))) {
  38. fullPath = joinURL(routerBase, fullPath)
  39. }
  40. // Avoid loop redirect
  41. if (decodeURI(fullPath) === decodeURI(ssrContext.url)) {
  42. ssrContext.redirected = false
  43. return
  44. }
  45. ssrContext.res.writeHead(opts.status, {
  46. Location: normalizeURL(fullPath)
  47. })
  48. ssrContext.res.end()
  49. }
  50. // This exported function will be called by `bundleRenderer`.
  51. // This is where we perform data-prefetching to determine the
  52. // state of our application before actually rendering it.
  53. // Since data fetching is async, this function is expected to
  54. // return a Promise that resolves to the app instance.
  55. export default async (ssrContext) => {
  56. // Create ssrContext.next for simulate next() of beforeEach() when wanted to redirect
  57. ssrContext.redirected = false
  58. ssrContext.next = createNext(ssrContext)
  59. // Used for beforeNuxtRender({ Components, nuxtState })
  60. ssrContext.beforeRenderFns = []
  61. // Nuxt object (window.{{globals.context}}, defaults to window.__NUXT__)
  62. ssrContext.nuxt = { layout: 'default', data: [], fetch: {}, error: null, state: null, serverRendered: true, routePath: '' }
  63. ssrContext.fetchCounters = {}
  64. // Remove query from url is static target
  65. // Public runtime config
  66. ssrContext.nuxt.config = ssrContext.runtimeConfig.public
  67. if (ssrContext.nuxt.config._app) {
  68. __webpack_public_path__ = joinURL(ssrContext.nuxt.config._app.cdnURL, ssrContext.nuxt.config._app.assetsPath)
  69. }
  70. // Create the app definition and the instance (created for each request)
  71. const { app, router, store } = await createApp(ssrContext, ssrContext.runtimeConfig.private)
  72. const _app = new Vue(app)
  73. // Add ssr route path to nuxt context so we can account for page navigation between ssr and csr
  74. ssrContext.nuxt.routePath = app.context.route.path
  75. // Add meta infos (used in renderer.js)
  76. ssrContext.meta = _app.$meta()
  77. // Keep asyncData for each matched component in ssrContext (used in app/utils.js via this.$ssrContext)
  78. ssrContext.asyncData = {}
  79. const beforeRender = async () => {
  80. // Call beforeNuxtRender() methods
  81. await Promise.all(ssrContext.beforeRenderFns.map(fn => promisify(fn, { Components, nuxtState: ssrContext.nuxt })))
  82. ssrContext.rendered = () => {
  83. // Add the state from the vuex store
  84. ssrContext.nuxt.state = store.state
  85. }
  86. }
  87. const renderErrorPage = async () => {
  88. // Don't server-render the page in static target
  89. if (ssrContext.target === 'static') {
  90. ssrContext.nuxt.serverRendered = false
  91. }
  92. // Load layout for error page
  93. const layout = (NuxtError.options || NuxtError).layout
  94. const errLayout = typeof layout === 'function' ? layout.call(NuxtError, app.context) : layout
  95. ssrContext.nuxt.layout = errLayout || 'default'
  96. await _app.loadLayout(errLayout)
  97. _app.setLayout(errLayout)
  98. await beforeRender()
  99. return _app
  100. }
  101. const render404Page = () => {
  102. app.context.error({ statusCode: 404, path: ssrContext.url, message: 'This page could not be found' })
  103. return renderErrorPage()
  104. }
  105. // Components are already resolved by setContext -> getRouteData (app/utils.js)
  106. const Components = getMatchedComponents(app.context.route)
  107. /*
  108. ** Dispatch store nuxtServerInit
  109. */
  110. if (store._actions && store._actions.nuxtServerInit) {
  111. try {
  112. await store.dispatch('nuxtServerInit', app.context)
  113. } catch (err) {
  114. console.debug('Error occurred when calling nuxtServerInit: ', err.message)
  115. throw err
  116. }
  117. }
  118. // ...If there is a redirect or an error, stop the process
  119. if (ssrContext.redirected) {
  120. return noopApp()
  121. }
  122. if (ssrContext.nuxt.error) {
  123. return renderErrorPage()
  124. }
  125. /*
  126. ** Call global middleware (nuxt.config.js)
  127. */
  128. let midd = []
  129. midd = midd.map((name) => {
  130. if (typeof name === 'function') {
  131. return name
  132. }
  133. if (typeof middleware[name] !== 'function') {
  134. app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
  135. }
  136. return middleware[name]
  137. })
  138. await middlewareSeries(midd, app.context)
  139. // ...If there is a redirect or an error, stop the process
  140. if (ssrContext.redirected) {
  141. return noopApp()
  142. }
  143. if (ssrContext.nuxt.error) {
  144. return renderErrorPage()
  145. }
  146. /*
  147. ** Set layout
  148. */
  149. let layout = Components.length ? Components[0].options.layout : NuxtError.layout
  150. if (typeof layout === 'function') {
  151. layout = layout(app.context)
  152. }
  153. await _app.loadLayout(layout)
  154. if (ssrContext.nuxt.error) {
  155. return renderErrorPage()
  156. }
  157. layout = _app.setLayout(layout)
  158. ssrContext.nuxt.layout = _app.layoutName
  159. /*
  160. ** Call middleware (layout + pages)
  161. */
  162. midd = []
  163. layout = sanitizeComponent(layout)
  164. if (layout.options.middleware) {
  165. midd = midd.concat(layout.options.middleware)
  166. }
  167. Components.forEach((Component) => {
  168. if (Component.options.middleware) {
  169. midd = midd.concat(Component.options.middleware)
  170. }
  171. })
  172. midd = midd.map((name) => {
  173. if (typeof name === 'function') {
  174. return name
  175. }
  176. if (typeof middleware[name] !== 'function') {
  177. app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
  178. }
  179. return middleware[name]
  180. })
  181. await middlewareSeries(midd, app.context)
  182. // ...If there is a redirect or an error, stop the process
  183. if (ssrContext.redirected) {
  184. return noopApp()
  185. }
  186. if (ssrContext.nuxt.error) {
  187. return renderErrorPage()
  188. }
  189. /*
  190. ** Call .validate()
  191. */
  192. let isValid = true
  193. try {
  194. for (const Component of Components) {
  195. if (typeof Component.options.validate !== 'function') {
  196. continue
  197. }
  198. isValid = await Component.options.validate(app.context)
  199. if (!isValid) {
  200. break
  201. }
  202. }
  203. } catch (validationError) {
  204. // ...If .validate() threw an error
  205. app.context.error({
  206. statusCode: validationError.statusCode || '500',
  207. message: validationError.message
  208. })
  209. return renderErrorPage()
  210. }
  211. // ...If .validate() returned false
  212. if (!isValid) {
  213. // Render a 404 error page
  214. return render404Page()
  215. }
  216. // If no Components found, returns 404
  217. if (!Components.length) {
  218. return render404Page()
  219. }
  220. // Call asyncData & fetch hooks on components matched by the route.
  221. const asyncDatas = await Promise.all(Components.map((Component) => {
  222. const promises = []
  223. // Call asyncData(context)
  224. if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
  225. const promise = promisify(Component.options.asyncData, app.context)
  226. promise.then((asyncDataResult) => {
  227. ssrContext.asyncData[Component.cid] = asyncDataResult
  228. applyAsyncData(Component)
  229. return asyncDataResult
  230. })
  231. promises.push(promise)
  232. } else {
  233. promises.push(null)
  234. }
  235. // Call fetch(context)
  236. if (Component.options.fetch && Component.options.fetch.length) {
  237. promises.push(Component.options.fetch(app.context))
  238. } else {
  239. promises.push(null)
  240. }
  241. return Promise.all(promises)
  242. }))
  243. // datas are the first row of each
  244. ssrContext.nuxt.data = asyncDatas.map(r => r[0] || {})
  245. // ...If there is a redirect or an error, stop the process
  246. if (ssrContext.redirected) {
  247. return noopApp()
  248. }
  249. if (ssrContext.nuxt.error) {
  250. return renderErrorPage()
  251. }
  252. // Call beforeNuxtRender methods & add store state
  253. await beforeRender()
  254. return _app
  255. }