By Yang Lei
I. Concept introduction
-
SPA (Single Page Application) : Single Page Application is a solution proposed when the front and back ends are separated. In an application or site, there is only one complete HTML page that has a container root node into which you can insert the code snippet that needs to be loaded.
- The working principle of SPA: the front-end route hops rotor page system, by changing the URL of the page, without re-requesting the page, the local update page view.
-
SEO (Search Engine Optimization) : Search Engine Optimization, the use of Search Engine rules to improve the natural ranking of the website in the relevant Search engines.
- How SEO works: When a web page is requested, the content sent out from the server can be crawled by the search engine crawler to the data. At this time, the keyword searched from the search engine is included in the content, so the information of the website is more easily displayed in the search results.
-
SSR (Server Side Rendering) : Server rendering places the initial request for data on the Server. When the Server receives the request, it fills the template with data to form a complete page, which is rendered and returned to the client.
-
CSR (Client Side rendering) : When a Client makes an HTML page request, the server returns a static HTML file without doing anything. Upon receipt, the client executes JavaScript, generates THE DOM, inserts the HTML page, and completes the drawing of the final page.
-
Isomorphic render: Front and back end isomorphism refers to the maintenance of the same code on the front and back ends. It is on the basis of SPA, using server rendering (SSR) straight out of the first screen, to remove the single page application (SPA) in the first screen rendering faced dilemma. To be clear, isomorphism is a solution that combines the advantages of the traditional pure service end straight out of the first screen and the advantages of SPA station experience, in order to obtain the optimal solution.
2. Advantages and disadvantages of server rendering and client rendering
Advantages of server-side rendering:
- First screen render fast
- Conducive to SEO
- The client resource usage is low
- Disadvantages of server-side rendering:
- Not conducive to the separation of front and rear end, low development efficiency
- The server consumes too many resources
Client-side rendering benefits:
- The network transmission data volume is small, reducing the server pressure
- Front and rear end separation, high development efficiency, easy maintenance
- Disadvantages of client-side rendering:
- Is not conducive to SEO
- First screen rendering is slow
3. Introduction to Next
Next. Js is not just a server-side rendering framework, but rather a isomorphic rendering framework. Next. Js has the best “developer experience” of its kind and many built-in features. Here are some of them:
- Intuitive, pt-based routing system (with support for dynamic routing)
- Pre-rendered. Support for static generation (SSG) and server side rendering (SSR) at the page level
- Automatic code splitting for faster page loading
- Client routing with optimized prefetch function
- Built-in CSS and Sass support, and support for any CSS-in-JS library
- The development environment supports quick refresh
- API routes Use Serverless Functions to build API endpoints
- Fully scalable
4. Core concepts for Next
Next. Js has two forms of pre-rendering: Static Generation and server-side Rendering. The difference between the two approaches lies in the timing of the HTML page generated for the page.
Static Generation
Static generation is where pages are generated at project build time and reused on each page request. The following figure illustrates the concept of static generation:
When to use static generation
The data needed to render the page is available at build time before the user requests it. The data is not intended for specific users and can be cached publicly. Common page types are:
- Marketing page
- Blog posts
- List of e-commerce products
- Help and Documentation
- How to use
Next. Js will pre-render the page at build time using the contain data returned by getStaticProps
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props}}Copy the code
Server side Rendering
Server-side rendering is the process of regenerating a page and returning it to the client at each request. The following figure illustrates the concept of server-side rendering:
When to use server-side rendering
It should be used only when the pre-rendered data for the page must be fetched on request, i.e. the page content is different each time it is requested. When a server rendered page is requested, Next builds the page based on the data returned by getServerSideProps.
export async function getServerSideProps(context) {
return {
props: {
// props for your component}}}Copy the code
routing
Nex.js has a file system router based on the concept of pages. When a file is added to the Pages directory, it is automatically treated as an available route. The naming of files in the Pages directory can be used to define most common routing patterns. The following are three routes matching modes, which are easy to understand: file path → corresponding route
The index routing
Pages /index.js → / pages/blog/index.js → /blogCopy the code
Embedded routines by
Pages/blog/first - post. Js - > / blogs/first - post pages/dashboard/Settings/username. Js - / dashboard/Settings/usernameCopy the code
Dynamic routing
Pages /blog/[slug].js → /blog/:slug (/blog/hello-world) pages/[username]/settings.js → /:username/ settings.js (/ foo/Settings) pages/post / [...] all js - / post / * (/ post / 2020 / id/title)Copy the code
If we use static generation and dynamic routing, we also need to use the getStaticPaths method, which must return objects with fallbacks and paths:
- Paths for pages that you want to use statically generated when building a project
- Fallback is a Boolean value
- If the value is true, when a user accesses a page that is not pre-rendered, the user does not jump to a 404 page. Instead, the user attempts to build a new page based on the new route, and an error is reported when the build fails
- If “false” is set to “false”, the user will jump to the 404 page when accessing a page without pre-rendering
export async function getStaticPaths() {
return {
paths: [{params: {... }}].fallback: true or false
};
}
Copy the code
Page jump
Use the Link component of Next for page jumping
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/post/abc">
<a>Go to pages/post/[pid].js</a>
</Link>
</li>
<li>
<Link href="/post/abc? foo=bar">
<a>Also goes to pages/post/[pid].js</a>
</Link>
</li>
<li>
<Link href="/post/abc/a-comment">
<a>Go to pages/post/[pid]/[comment].js</a>
</Link>
</li>
</ul>)}export default Home
Copy the code
Use useRouter for programmatic navigation
import { useRouter } from 'next/router'
function ReadMore() {
const router = useRouter()
return (
<span onClick={()= > router.push('/about')}>Click here to read more</span>)}export default ReadMore
Copy the code
API routing
Next. Js provides a solution for building apis, similar to the way routes are used above. Files added in the “pages/ API” directory are mapped to the “/ API /*” API.
At project build time, the files under “pages/ API” will not increase the size of the client package, only the server package.
/ / pages/API/user. Js > / user
export default function handler(req, res) {
res.status(200).json({ data: 'hello API'})}Copy the code
Dynamic API routing is used in a similar way to dynamic routing mentioned above
Pages/API /post/.js → / API /post/:pid (/ API /post/1) ABC)/API/post/pages/API/post/slug [...] and js/API/post / * (1/2 / API/API/post / / post/a/b/c)Copy the code
The environment variable
Next. Js allows developers to create three files in the project root directory to store different environment variables
- .env (all environments)
- .env.development (development environment)
- .env. Production
It is then obtained by process.env. Variable name
// Set environment variable DB_HOST=localhost DB_USER=myuser DB_PASS=mypasswordCopy the code
Export async function getStaticProps() {const db = await mydb.connect ({host: process.env.db_host, username: process.env.DB_USER, password: process.env.DB_PASS, }) }Copy the code
By default, environment variables are used on the server side of Node.js. If you want to use environment variables in the browser, you need to add NEXT_PUBLIC_ to the environment variable to expose it to the browser side:
NEXT_PUBLIC_HELLO=hello
Copy the code
Built-in CSS support
Nex.js allows developers to import SCSS/CSS files in JavaScript files.
Adding global Styles
To add a global style, you need to use a custom App
All you need to do is add a _app.js file in the Pages directory and import the global stylesheet into it.
import '.. /global.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {. pageProps} / >
}
Copy the code
Add component-level style modules
For a developer to use a style module, the style file must be named one of the following:
- *.module.css
- *.module.scss
CSS Modlue defines CSS locally by automatically creating unique class names, which allows developers to use the same CSS class names in different files without fear of conflict.
// button.module.css
.error {
color: white;
background-color: red;
}
// Button.js
import styles from './button.module.css'
export function Button() {
return (
<button
type="button"
// Note how the "error" class is accessed as a property on the imported/ / `styles` object.
className={styles.error}
>
Destroy
</button>)}Copy the code
5. Reference documents
- Next. Js official documentation
- Talk about my understanding of server-side rendering (SSR)