Next.JS: How to make ALL requests server-side

浪子不回头ぞ 提交于 2019-12-03 00:28:49

I found a solution by wrapping Next.JS in Express!

I have pushed a simple example project to GitHub here

The repo has a nice README as well as comments in the code that detail what's going on.

Quick rundown:

  • Wrap Next.JS in an express server. Explicitly render pages by calling nextApp.render(...) which happens implicitly in standard Next.JS apps. See server.js
  • Use express routing. Make server-side requests prior to rendering the pages with nextApp.render(...). See server.js.
  • Use standard anchor tags to ensure that pages requests hit the express server. See index.js
  • nextApp.render provides passed values to the page in the context (ctx) parameter of getInitialProps. You can make these values available in the pages this.props by returning them in getInitialProps. See stars.js

Suggestions and improvements welcome!

This is generally a bad idea.

The entire point of an SPA is to prevent full page loads.

You can use getInitialProps to fetch stuff while on the initial page request, and on subsequent navigations, as it is called for every page.

Next is encouraging you to use an API to talk to the server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!