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

3

9

I am building a Next.JS app that will be getting data from a Python API and an Postgres Database.

Normally this would be simple, except requirements are such that I need to send all requests from the server-side, not the user's client.

I have been working with and grokking getInitialProps, but I am not confident that it is the full solution that I need because of this line in the README:

For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.

It seems that getInitialProps is designed for the initial page load, and not for subsequent server-side data fetching.

How can I design my Next.JS app in such a way that all requests come from the server-side?

Notes:

  • It is OK that every request essentially results in an initial page load.
  • It is OK for the user Client to talk back to the Node (Next.JS) server since it's publicly-exposed. I am currently experimenting with wrapping Next.JS in an express server.

Ty in advance for any help

Incisor answered 20/4, 2018 at 22:3 Comment(0)
I
16

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!

Incisor answered 23/4, 2018 at 18:35 Comment(1)
Good job! It's similar to RazzleFere
O
1

I thinks this is done simply with getServerSideProps() Official Docs. It's as simple as it says really: "If you export an async function called getServerSideProps from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps"

Obscenity answered 28/1, 2021 at 17:48 Comment(0)
M
0

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

Meuse answered 10/3, 2019 at 21:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.