-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotes.txt
189 lines (151 loc) · 11.1 KB
/
notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//////- Routing -////
1. Simple Route >> index.js
2. Nested Routes >> blog example
3. Dinamic Routes >> Product example
4. Catch all Routes >> docs/[[params]] example
// <LINK>
- For client-side routing
- history can be deleted using "replace" >> browser's go back button will birng us to the root page
// Programmatic Navigation
<button onClicl={handleClick}/>
- router.push("/product")
- router.replace("/product") >> to replace history
// 404.js in pages directory >> handle undefined routes
-------------------------------------------------------------------------------------------
//////- How to fetch data -////
- getStaticProps and getServerSideProps
-------------------------------------------------------------------------------------------
//////- getStaticProps function -////
1. Runs ONLY on the server-side
- Never run client-side >> Won't be included in the JS bundle sent to the browser
2. You can write server-side code DIRECTLY in it
- Access to filesystem with "fs" or querying database can be done inside it
- Don't have to worry about incuding API-KEYS in it, as that won't make it to the browser either
3. It can ONLY run inside a PAGE component, cannot run in regular components
- ONLY used for pre-rendering and NOT for client-side data fetching
4. Should return an OBJECT which should have a PROPS KEY which is also an OBJECT
5. It will run in build time, during development it runs on every request
//////- getStaticProps function -////
1. To tell Next.js which pages to pre-render statically
2. Should return an OBJECT with a /paths key
//////- getServerSideProps function -////
1. It runs ONLY on the server side,
- It will NEVER run clien-side
- The code you write inside getServerSideProps won't be included in the JS bundle that is sent to the browser
2. You can write server-side code directly in getServerSideProps
- Access to filesystem with "fs" module or querying a database can be done inside it
- Don't have to worry about incuding API-KEYS in it, as that won't make it to the browser either
3. It can ONLY run inside a PAGE component, cannot run in regular components
- ONLY used for pre-rendering and NOT for client-side data fetching
4. Should return an OBJECT which should have a PROPS KEY which is also an OBJECT
5. It will run at REQUEST time
-------------------------------------------------------------------------------------------
//////- BUILD -////
1. Any <LINK/> component in the viewport will be prefetched by default (including the corresponding data) for pages using STATIC GENERATION
2. When a page with getStaticProps is pre-rendered at build time, in addition to the HTML files, Next.js generates a JSON file holding the result of the running getStaticProps too
- The JSON file will be used in CLIENT-SIDE routing through NEXT/LINK, or NEXT/ROUTER
3. If we navigate directly by writing the link in the browser, the HTML file will be loaded. If we navigate from anouther ROUTE, the page will be generated client-side by pre-fetching Javascript+JSON from the server
-------------------------------------------------------------------------------------------
//////- Two forms of PRE-RENDERING -////
1. Static Generation (recommended most of the times)
2. Server-side Rendering
//////- 1. Static Generation & Issues -////
- Static generation is a method of pre-rendering where the HTML pages are generated at build time.
- The pre-rendered static pages can be pushed to a CDN, cached, served to clients across the globe almost instantly and reused for each request
- Static content is fast and better for SEO as they are immediately indexed by search engines
- Static generation with "getStaticProps" for data fetching and "getStaticPaths" for dynamic pages seems like a really good approach to a wide variety of appllications in production
- For dynamic page with "getStaticPaths" and fallback set to TRUE the page is not generated at build time but is generate on the initial request
// Issues:
1. Issues with build time:
The build time is proportional to the number of pages in the appllication
Example:
- A page takes 100ms to build.
- E-commerce app with 100 products takes 10 seconds to build.
- E-commerce app with 100.000 products takes >2.5 hours to build.
- It's not just the time, there are cost implications as well.
The problem gets worse with more products you add to the system as every new page increases the overall build time.
2. Issues with stale data:
A page, once generated, can contain stale data till the time you rebuild the application.
Depending on the nature of your appllication, you might run into the issue of stale data.
Example:
- E-commerce app is not an application which you can build and deploy once in a while. Product details, especially product prices can vary everyday.
- Even if only the price of a product changed, the entire app has to be re-built and the page with updated data will be statically generated
Can getStaticPaths help?
Pre-render only a few pages at build time and rest of the pages can be pre-rendered on request?
- getStaticPaths only works for dynamic pages, if your app has 90% static pages and 10% dynamic pages, getStaticPaths will not help much.
- However an e-commerce site typically will have 90% dynamic pages and 10% static pages. So we can reduce the total build time by using getStaticPaths.
- But it still does NOT fix the issue of STALE data..
- If you render 1000 pages at build time, and then the rest are generated based on incoming request, using 'fallback: TRUE' or 'fallback: BLOCKING', changes in data will NOT update the already pre-rendered pages
- We cannot fetch data at request time! (E.g in case if a news website, you cannot afford to have stale data..)
//////- Incremental Static Regeneration (ISR) -////
There was a need to update only those pages which needed a change without having to rebuild the antire app
- With ISR, Next.js allows you to update static pages after you've built you app
- You can statically generate individual pages without needing to rebuild the entire site, effectively solving the issue of dealing with stale data
// How?
In the "getStaticProps" function, apart from the props key, we can specify a "REVALIDATE" key
- The value for revalidate is the number of secs after which a page re-generation can ouccur
// Re-generation
A re-generation is initiated only if a user makes a request after the revalidate time
- If a user visits our product details page but there is no other user hitting that page the entire day, the re-generation does not happen.
- Revalidate (10sec) does NOT MEAN the page automatically re-generates every 10 seconds!
- It simply denotes the time AFTER which, if a user MAKES a request, a re-generation has to be initiated!
- The re-generation can also fail and the previously cached HTML could be served till the subsequent re-generations succeed.
// Issues:
1. We cannot fetch data at request time:
Example:
In case a news website, you cannot afford to have stale data even for 1 second!
- Incremental static generation can help in many cases, but if revalidate is 1 sec, we still might not always see the most up to date news when the regeneration is happening in the background..
2. We don't have access to the incoming request:
Example:
Problem in case the data that needs to be fetched is SPECIFIC to the user..
E.g we are building a website similar to twitter
- As a user, I should be able to see tweets that are persionalized based on my interests
- The tweets that I see also need to be SEO FRIENDLY as it is public content that anyone in the world can see..
- To fetch tweets specific to the user, we need the userId. And that can be obtained only if we have access to the incoming request
- You could do it client side in "useEffect" for example but that means you again miss out on SEO!
-------------------------------------------------------------------------------------------
//////- 2. SERVER-SIDE RENDERING (SSR) -////
- Next.js allows you to pre-render a page not at build time but at request time
- The HTML is generated for every incoming request
- So SSR is a form of pre-rendering where the HTML is generated at request time
- SSR is required when you need to fetch data per request and also when you need to fetch personalized data keeping in mind SEO
This form of rendeing is slower than static generation as the server must compute the result on every request, so USE server-side rendering ONLY if absolutely necessary!
// How?
//////- getServerSideProps function -////
-------------------------------------------------------------------------------------------
//////- CLIENT-SIDE DATA FETCHING -////
You might not always need to pre-render the data
Example: (dashboard.js + dashboard-swr.js)
User dashboard page
- It is private, that is behind a login screen
- Highly user specific, SEO is not relevant
- No need to pre-render data
So you can rely on client side data fetching!
/// SWR - a React Hooks library for Data Fetching (stale-while-revalidate)
- https://swr.vercel.app
- it is a much simpler solution for data fetching than using the useEffect+useState hooks
PLUS:
- if we use useEffect+State hooks for fetching, if there is a change in the database, the browser has to be refreshed to see the latest data
- however in case we use SWR, the SWR hook will automatically fetch the latest data and the UI is updated without refreshing the browser !!
-------------------------------------------------------------------------------------------
//////- CLIENT-SIDE DATA FETCHING + PRE-RENDERING -////
Example: (events.js)
Event Listing Page
- A page that shows a list of events happening around you
- Since We want SEO + Request time data fetching
>> We'll use Server-side rendering with getServerSideProps
- Once events have been loaded, we're going to use CLIENT-SIDE DATA FETCHING to filter the events
// fetch all events for SEO purposes first, but filter the events client-side with fetchSportEvents for the user, but the URL will still stay the same (user cannot share his filtered results as a link)
// for that we have to use shallow routing >> with which you can update URL in the browser without running the code inside getServerSideProps
// >> define the CONTEXT parameter > query > category
//add the route to the URL in the browser:
router.push('/events?category=sports', undefined, { shallow: true })
-------------------------------------------------------------------------------------------
//////- API ROUTES -////
Next.js is a fullstack framework (./NEXT-API-ROUTES/pages/api)
- You can write the frontend code in React and also write APIs that can be called by the front end code
- API routes allow you to create RESTful endpoints as part of your Next.j app folder structure
- Within the pages folder, you need to create a folder called 'api'
- Withing that 'api' folder, you can define all the APIs for you app
- You can add business logic without needing to write any additional custom server code and without having to configure any API routes
- Next.js gives you everything you need to write a full-stack React+Node app