server.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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) || '/'
  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, serverRendered: true, routePath: '' }
  63. ssrContext.fetchCounters = {}
  64. // Remove query from url is static target
  65. if (ssrContext.url) {
  66. ssrContext.url = ssrContext.url.split('?')[0]
  67. }
  68. // Public runtime config
  69. ssrContext.nuxt.config = ssrContext.runtimeConfig.public
  70. if (ssrContext.nuxt.config._app) {
  71. __webpack_public_path__ = joinURL(ssrContext.nuxt.config._app.cdnURL, ssrContext.nuxt.config._app.assetsPath)
  72. }
  73. // Create the app definition and the instance (created for each request)
  74. const { app, router } = await createApp(ssrContext, ssrContext.runtimeConfig.private)
  75. const _app = new Vue(app)
  76. // Add ssr route path to nuxt context so we can account for page navigation between ssr and csr
  77. ssrContext.nuxt.routePath = app.context.route.path
  78. // Add meta infos (used in renderer.js)
  79. ssrContext.meta = _app.$meta()
  80. // Keep asyncData for each matched component in ssrContext (used in app/utils.js via this.$ssrContext)
  81. ssrContext.asyncData = {}
  82. const beforeRender = async () => {
  83. // Call beforeNuxtRender() methods
  84. await Promise.all(ssrContext.beforeRenderFns.map(fn => promisify(fn, { Components, nuxtState: ssrContext.nuxt })))
  85. }
  86. const renderErrorPage = async () => {
  87. // Don't server-render the page in static target
  88. if (ssrContext.target === 'static') {
  89. ssrContext.nuxt.serverRendered = false
  90. }
  91. // Load layout for error page
  92. const layout = (NuxtError.options || NuxtError).layout
  93. const errLayout = typeof layout === 'function' ? layout.call(NuxtError, app.context) : layout
  94. ssrContext.nuxt.layout = errLayout || 'default'
  95. await _app.loadLayout(errLayout)
  96. _app.setLayout(errLayout)
  97. await beforeRender()
  98. return _app
  99. }
  100. const render404Page = () => {
  101. app.context.error({ statusCode: 404, path: ssrContext.url, message: 'This page could not be found' })
  102. return renderErrorPage()
  103. }
  104. // Components are already resolved by setContext -> getRouteData (app/utils.js)
  105. const Components = getMatchedComponents(app.context.route)
  106. /*
  107. ** Call global middleware (nuxt.config.js)
  108. */
  109. let midd = []
  110. midd = midd.map((name) => {
  111. if (typeof name === 'function') {
  112. return name
  113. }
  114. if (typeof middleware[name] !== 'function') {
  115. app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
  116. }
  117. return middleware[name]
  118. })
  119. await middlewareSeries(midd, app.context)
  120. // ...If there is a redirect or an error, stop the process
  121. if (ssrContext.redirected) {
  122. return noopApp()
  123. }
  124. if (ssrContext.nuxt.error) {
  125. return renderErrorPage()
  126. }
  127. /*
  128. ** Set layout
  129. */
  130. let layout = Components.length ? Components[0].options.layout : NuxtError.layout
  131. if (typeof layout === 'function') {
  132. layout = layout(app.context)
  133. }
  134. await _app.loadLayout(layout)
  135. if (ssrContext.nuxt.error) {
  136. return renderErrorPage()
  137. }
  138. layout = _app.setLayout(layout)
  139. ssrContext.nuxt.layout = _app.layoutName
  140. /*
  141. ** Call middleware (layout + pages)
  142. */
  143. midd = []
  144. layout = sanitizeComponent(layout)
  145. if (layout.options.middleware) {
  146. midd = midd.concat(layout.options.middleware)
  147. }
  148. Components.forEach((Component) => {
  149. if (Component.options.middleware) {
  150. midd = midd.concat(Component.options.middleware)
  151. }
  152. })
  153. midd = midd.map((name) => {
  154. if (typeof name === 'function') {
  155. return name
  156. }
  157. if (typeof middleware[name] !== 'function') {
  158. app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
  159. }
  160. return middleware[name]
  161. })
  162. await middlewareSeries(midd, app.context)
  163. // ...If there is a redirect or an error, stop the process
  164. if (ssrContext.redirected) {
  165. return noopApp()
  166. }
  167. if (ssrContext.nuxt.error) {
  168. return renderErrorPage()
  169. }
  170. /*
  171. ** Call .validate()
  172. */
  173. let isValid = true
  174. try {
  175. for (const Component of Components) {
  176. if (typeof Component.options.validate !== 'function') {
  177. continue
  178. }
  179. isValid = await Component.options.validate(app.context)
  180. if (!isValid) {
  181. break
  182. }
  183. }
  184. } catch (validationError) {
  185. // ...If .validate() threw an error
  186. app.context.error({
  187. statusCode: validationError.statusCode || '500',
  188. message: validationError.message
  189. })
  190. return renderErrorPage()
  191. }
  192. // ...If .validate() returned false
  193. if (!isValid) {
  194. // Render a 404 error page
  195. return render404Page()
  196. }
  197. // If no Components found, returns 404
  198. if (!Components.length) {
  199. return render404Page()
  200. }
  201. // Call asyncData & fetch hooks on components matched by the route.
  202. const asyncDatas = await Promise.all(Components.map((Component) => {
  203. const promises = []
  204. // Call asyncData(context)
  205. if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
  206. const promise = promisify(Component.options.asyncData, app.context)
  207. promise.then((asyncDataResult) => {
  208. ssrContext.asyncData[Component.cid] = asyncDataResult
  209. applyAsyncData(Component)
  210. return asyncDataResult
  211. })
  212. promises.push(promise)
  213. } else {
  214. promises.push(null)
  215. }
  216. // Call fetch(context)
  217. if (Component.options.fetch && Component.options.fetch.length) {
  218. promises.push(Component.options.fetch(app.context))
  219. } else {
  220. promises.push(null)
  221. }
  222. return Promise.all(promises)
  223. }))
  224. // datas are the first row of each
  225. ssrContext.nuxt.data = asyncDatas.map(r => r[0] || {})
  226. // ...If there is a redirect or an error, stop the process
  227. if (ssrContext.redirected) {
  228. return noopApp()
  229. }
  230. if (ssrContext.nuxt.error) {
  231. return renderErrorPage()
  232. }
  233. // Call beforeNuxtRender methods & add store state
  234. await beforeRender()
  235. return _app
  236. }