There are many ways to fetch data from apis in next.js.
getServerSideProps,getStaticPaths,getStaticProps,Incremental Static
Regeneration and client side rendering.
If I have to make requests to backend on the change of any state, can I use other methods of data fetching apart from client side rendering?
I am from React.js background where client side rendering is mostly used.
What are the specific use cases of different fetching methods?
Can I always use client side rendering only in Next.js also.
Server-side rendering is good for SEO. You can check this, if you view the page source of a react app you won't get much HTML, this is the problem next.js fixes. With getServerSideProps and getStaticProps you can make calls to your API(such as DB back-end) to get your data and server-side render your page. Now when you have to update state of your page you can simply fetch as you normally would, since it doesn't matter because it is triggered by some action anyway.
Can I always use client side rendering only in next.js also.
Yes you can, but you want search engines to index your site and/or display relevant data such as review and preview text, right?
If I have to make requests to backend on the change of any state, Can I use other methods of data fetching apart from client side rendering
When the state is changed you will fetch new information just like you normally did in react.
GetServerSideProps and GetStaticProps only run once when the user visits the page(or reloads etc ofc). You can get the latest data by fetching and updating state with that.
Next.js is much more than react, it can be used as a back-end too i.e. creating APIs for saving data to db, handle authentication etc. Explaining it all is beyond the scope of this answer.
As for when to use what you can read more about it here, or search about it I'm sure SO has many questions about this.
One situation where you can be forced to use next.js features is when you want to consume an old API that does not implement CORS, here you can't control the dev on the other side so you can create an API on next.js which you fetch on your react code like: /getinfo. Now write code on your back-end to handle this which will delegate the result of that third-party API back to you, pretty neat right
Related
I know about ssr (server side rendering) in Vue, such as nuxt. It grabs data in serverPrefetch() function and renders content on server side, only after then the request is returning data to user and he is starting to download app.js.
But can we start loading data from backend immediatelly after user request, not waiting for download of vue script, and not stalling request before all data is loaded. So user is downloading app.js, while our server is doing work with sql requests and forming response.
As long as Nuxt is concerned - you can find a pretty good summary on the SSR (and client-side) options available in the following article. Spoiler alert - I think SSR is still the best shot with what you are trying to achieve. In the Nuxt world - NuxtServerInit and AsyncData are the men for the job.
Say you decided to stay away from SSR - what options do you have?
Have some super lightweight js loaded and ran before the Vue application that would fetch the data and share it with the app somehow (e.g. - saving it to the local storage). Would it really provide a speed advantage? I really doubt it, especially considering how fast the Vue app could load when cached in the client browser.
Dump the backend data into the server response itself. I mean, you could prefetch all the heavy stuff and stick it into your page as a json encoded object. That would save some time for initial requests for sure, but then - how large is that data chunk? Wouldn't it make the initial load too heavy, destroying the initial purpose? Those are the questions you should answer based on your particular use case.
In the Next.JS documentation I read the following.
Note: You should not use fetch() to call an API route in getStaticProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach.
Fetching from an external API is fine!
But if I'm not supposed to use the internal API then two questions arise.
How can I handle POSTS? Should I handle POSTS / PUTS etc through the API but not GETS? That seems odd to me.
If I also should not do 'internal POSTS etc' why is the API option there?
edit:
Hmm. I suppose one of the reasons is that when using getStaticProps, and compiling a static version of the site, # compile time the API is potentially not running. But that could be easily solved by running the API at the same time. (Since GetStaticProps is not really relevant for interactive pages, so POST etc)
edit2:
Someone here also figure that out. Next.js - Error: only absolute urls are supported run export and sever separately and then you can do fetch in static props when needed. Then at least all stuff is in one place.
The function getStaticProps is meant to generate the data on the server-side when the page is loaded.
Answer 1: You should handle POST/PUT/GET, etc in your API routes.
Answer 2: The main difference between getStaticProps and API is the time they are run. getStaticProps is run when the page is generated on the server. API can be called anytime you need them.
I am very used to the approach where SSR meant that the page got a full refresh and received a full HTML from the server, where it gets rendered with razor/pub/other depending on the backend stack. So every time the user would click on the navigation links, it would just send a request to the server and the whole page would refresh, receiving a new HTML. That is the traditional SSR which I understand.
With SPA however, we have for example react or angular, where we receive almost empty HTML on the beginning and then the JS so that the whole app gets initialized on the client side. We can then have some REST API to get json data and render views on the frontend (client side routing and rendering) without any page refresh. We don't even need any server really.
Now, what I have a problem understanding is how SSR (such as next.js) works with react.
From what I am reading, the first request returns full HTML+CSS (which helps with SEO etc - I get that), but what happens later? What happens after that first/initial request? Does the whole react app initialize in the browser and then it just behaves EXACTLY as if it was a normal SPA (meaning we have client side routing and rendering from now on, without any need to make requests to that server)? In other words, does next.js still make any server requests after the initial one, or does it act like a typical SPA with CRA from now on?
I spent lots of time reading but all the articles mainly focus on the initial request and SEO and time to first byte, paint etc. and I am simply trying to understand why its called SSR since it seems to work different than the traditional SSR which I described on the beginning.
does next.js still make any server requests after the initial one, or does it act like a typical SPA with CRA from now on?
You got it right. The first (initial) request is handled by the server and after that the frontend handles the routing (at least in the case of Next.js).
If you want to see an example OpenCollective is built with Next.js. Try playing around with it and see the Network tab in the DevTools.
I am simply trying to understand why its called SSR since it seems to work different than the traditional SSR which I described on the beginning.
It is called SSR because the app is effectively being rendered on the server. The fact that frontend routing takes over after the initial render doesn't remove the fact that the server did the work of rendering the app as oppose to the user machine.
That's Not all the things that happen with Next.js, In Next.js You can build something called Hybrid apps.
In traditional SSR, all of your client requests get handled by the server. Every request goes to the server and gets responses.
In classic CSR with something like React, as you said, all the things happens in the browser via the client-side javascript.
But, in Next.js you can define three different approaches (mainly two according to the docs) for pages to get delivered.
based on the app needs and requirements, you can serve a couple of pages in pure traditional SSR mode, a couple of them in classic CSR mode, and a couple of in SSR mode via dynamic data that get fetched and rendered into the pages on the fly.
these features bring lots of flexibility to design a web-app that behaves perfectly in every different scenario that is needed.
I'm building an app that receives updates from an external source. (Let's say the updates are stock quotes, that come in sporadically, every 10-60 seconds.)
Each client page might display the full list of interesting stocks, or focus on a single stock. Components on any page should update as the server receives new data for stocks displayed on that page.
My questions:
Will react, react, react-redux modules handle the communication between the server-side updates and the client components in the browser out-of-the-box? (Obviously I will have to write the actions/reducers/etc.) Or will I also need to write code that communicates those updates from the server to the clients?
I envision starting up the server-side process that receives stock updates from the main server.js code that also fires off the listen(3000) call. How could that stock-update process get access to the redux store? (My confusion comes because in most of the Express examples I've read, the createStore() call is within the app.use('/', ...) so the store gets generated each time a new web request comes in.)
Any pointers to projects similar to what I want to do? Thanks.
You will have to write code that communicates updates from server to the clients. The best way to do this would be use websockets. You can use frameworks like http://socket.io/ etc.
The Express samples that you have come across that use createStore on the server side are for server side rendering. Accessing store here to push stock updates is not preferred.
In Brief, what you need to do is ,
Set up socket io or websocket server
On the client, set up a socket-io client. It waits for messages from server.
Whenever you get stock updates, send the data from server to client through socket io.
When the client receives the message, dispatch an action with the data and let redux flow handle the state/store.
nope neither react no redux handles communication between serverside and react components (clientside)
react works as an ui view
redux manages application state
communication between server and client fall into actions and action creators in this case you could make an ajax call to server (by polling) and the state could be a boolean fetching, fetched,faliure all of which need to be managed in the store together with the response object.
Regarding the issue of serverside stock-update process,it doesn't matter since only the implementors understant what the initial state is hence the question to ask is does it matter to you that the createstore() is being called and what is it's initial state of the application.
on your case the createStore could be configured in such a case that its an reducer that fetches the stock at the point in time from the main server.js
you may also want to check
relay and graphql which comes with networking layer for communication to server by default all of which try to manage application state
[Answering my own question] The responses from various contributors above are correct and quite useful, but I have been (re)learning how to structure apps with react and redux. I wanted to share my new knowledge:
Christophe Coenraets wrote a blog posting that exactly matches my use-case: Real Time Trader Desktop with React, Node.js, and Socket.io
I write a blog posting that summarizes what I have learned about getting started with React programming in mid-2016: Getting Started with React Development
I am looking at express.js for the back end and JS on the client side.
My app is a single page Web App.
The server will only serve JSON messages and my question is about "routing" for express.
Is one supposed to use routing to connect the UI and the server side business logic?
How will that work with my single page app?
so lets say, the client makes an Ajax call to the server looking for a value in the database and there is server side script that provides the JSON back to the UI. How is this UI and node script relationship setup?
Can someone shed some light on this?
Single page apps are those that live on a single HTML document. This means that if you want to display some different content to the user, depending on the state of the application, you will need to do some DOM manipulation (cutting out and replacing certain elements of the current document with different HTML) in order to update the 'view' that the user sees. Excuse me if this is obvious to you, please don't take offense. I figured I'd start from here. Hang with me and I'll explain how your routing situation is going to play out (more or less).
URLs are composed of a few different parts, each of which informs the browser of a particular bit of information that is required in order to download the resource that the user is attempting to access. Typically the resources that you are looking for are off on a server somewhere and the browser knows this because of pieces in the URL like 'protocol' ('http:') and 'host' ('www.mydomain.com'), so it goes off to that server to find what you're requesting. There are also 'query' parameters in URLs which provide some additional information to the server regarding a particular action, like the search terms of a search query. After the query parameters, comes the 'hash'. The hash is where the magic of single page apps happens... eh, well, kind of.....
First a bit about the hash. When you add a '#' to a URL, the browser then interprets the information that comes after it to be some location (element) within the currently displayed document. That means, if you have an element with an 'id' of 'main' and you add '#main' to the end of the URL, like so: 'http: //www.example.com#main', the browser will 'scroll' (typically 'jump') to the beginning of that element, so that the you can see it. Be aware, though, that if you type 'http://www.example.com/#main' (with the hash separated from the URL by a slash) then you will force a complete page reload and the browser will attempt to find a file by the name '#main' on the server (I bet it doesn't find it).
The takeaway here is that the browser will not attempt to navigate away from the current document if there is a hash in the URL, the exception being of course the case mention above, and this is great because single-page apps don't want to navigate away from the page or request a new document from the server. (See how routing is different for single-page apps?)
Now, this whole thing about the hash isn't vital to single-page apps, as you could make one without dealing with it all. A bunch of click handlers and DOM manipulation is all you'd need really... But, that would mean that users will have no way of sharing links to particular views in your app. The URL would never change, and we would never be able to navigate to any particular view directly. We'd always be starting from the starting position of your app, which could easily be a very annoying situation.
If your single-page app is going to have different views, and you want users to be able to navigate directly to particular ones via bookmarks or links, then you will need to implement a form of routing on the front-end in addition to the routing that you'll need to implement on the backend (routing for data API, etc.), which means that you will need to make use of the hash.
I don't want to get into how different frameworks accomplish routing on the front-end, but it's basically a matter of updating the browser's address field when the user clicks a link, and watching the address bar to determine what the current URL is and loading the HTML that is associated with that URL into the DOM in the designated location in the document tree.
So, within a single-page app, you have one route on the server that deals with rendering the app HTML document (index.html), and you have routes that are responsible for dealing with the data of your app (creating new instances in the database, logging in and out, editing or destroying instances in the DB, and fetching data...) which are called via AJAX requests.
This is actually a fairly complicated situation in that HTML5 allows us to be able to forgo the hash (with the help of some link rewriting on the server) and also be able to use the 'back' and 'forward' buttons as if we've actually navigated away from the original document (which we haven't because we have only pointed the browser to the exact same URL, only with modified hash values, so no new page loads have occurred). Traditional site navigation and linking can be achieved by utilizing the browser's History API, which is available for IE beginning with version 10 (I believe), the rest of the big browser vendors were already on to it quite a bit earlier, so frameworks that leverage this technology will allow your users to navigate your app without the hash in the URL. Explaining this is a diversion and not necessary for understanding routing in single-page apps, but it is interesting and you'll have to learn it eventually anyway, probably..
AJAX should be used to request JSON from the server. AJAX requests will always hit your server because you don't include the hash symbol in AJAX requests (it would be ridiculous to do so because the hash is meant only for in-document browsing), so server-side routes must be responsible for exposing your data API (consider a RESTful one). While this is not their sole purpose in single-page apps, it is perhaps their most important one.
Soooo, to wrap it up, you will have two sets of routes. One on the client (as part of a client-side framework like AngularJS or EmberJS, the list goes on... I prefer Angular, but there is a fairly steep learning curve for that one.), and one on the server. When you think about 'server routes' think data API. When you think of 'page routing', remember that this all gets handled on the client, by the javascript that you delivered with the initial server response (this is the one and only necessary server-side route involved with rendering HTML to the browser, loading your 'index.html' and all of the necessary scripts and stylesheets, etc). You will use express.static middleware to serve static files, so you don't have to worry about assigning routes for that stuff.
EDIT A quick mention of AJAX implementation.
On the server, you will have routes similar those that Alex has provided as examples and you will make calls to those URLs from the client using whatever XMLHttpRequest (XHR) object is exposed by your framework or library of choice. It is now considered more or less standard and best practice for frameworks/libraries to implement these requests as Promises http://wiki.commonjs.org/wiki/Promises/A. You should read a bit about it on your own, but I might be able to summarize it by saying that it is an asynchronous operation analogous to 'try, catch, throw' in synchronous operations. You will instantiate a promise object and through it you will attempt to load data from the server, for instance, via GET request. Make sure that you have assigned functions to handle requests made to the URL that you made the request to (server-side route)! This object that you instantiate and subsequently make the request to the server through, promises to return the result of the request to you once it comes back from the server (no matter whether it was successful or not) If it is successful, it will call a function that you have written and will supply it with the data from the server. If it fails, it will call a different function, also written by you, and will supply it with the error object (or 'reason' for failure), so you can handle the error appropriately.
Hope that helped answer your question.
You only have to route requests you serve dynamically. Your HTML, CSS, JS are all static assets. So all you need to handling routing for is your data.
It sounds like you want a Restful API, which basically means that you have URLs for specific resources, and HTTP verbs for manipulating them.
Something like:
GET /books.json - Get all books
POST /books.json - Create a new book with properties passed in the body of the request
GET /books/123.json - Get book with id of 123
PUT /books/123.json - Update an existing book with properties passed in the body of the request
This blog post seems to show how to set this up in Express.
Once you have a sane API delivering JSON, you just make your AJAX calls use it based on what objects you want to fetch.