Next. Js is the React server rendering application framework for building SEO-friendly SPA applications.
Next. Js supports two pre-rendering modes, static generation and server-side rendering, zero configuration of routing system based on page, automatic code splitting and optimized page loading speed. Supports static export. You can export applications as static websites. Styled – JSX with the built-in CSS-in-JS library.
The solution is mature and can be used in a production environment and is used by many companies around the world. The application is easy to deploy, has its own deployment environment Vercel, and can be deployed in other environments.
Create the Next. Js project
npm init next-app next-guide
npm run dev
Copy the code
-
- Create the page
In Next. Js, the page is placed in the React component in the Pages folder. The component needs to be exported by default.
pages/list.js
export default function List () {
return <div>List</div>
}
/ / access
// localhost:3000/list.html
Copy the code
-
- Page jump
A component Link is needed to realize page jump. By default, Javacript is used for page jump, which is in the form of SPA.
A link jump is used if JavaScript is disabled in the browser. No attributes other than the href attribute should be added to the Link component; the remaining attributes are added to the A tag.
The Link component automatically optimizes the application for best performance with prefetch capabilities. That is, when the browser is idle, the Link component will pre-load the content of the page in Link. When we visit the page, it is already finished, and the page will be fast.
import Link from 'next/link';
<Link href="/list"><a title="title">list page</a></Link>
Copy the code
Resource file
The application and the public folder in the directory provide static resources
You do not need to write a public path to access the file in the following form.
pulic/images/1.jpg -> /images/1.jpg
- Modify the source data on the page
This can be done through the Head component, which allows you to customize the source data for the web page.
import Head from 'next/head';
<>
<Head>
<title>Index Page</title>
</Head>
</>
Copy the code
- CSS styles
Styleshad-jsx is built into next.js, which is a CSS-in-JS library that allows you to write CSS in the React component. CSS is scoped only inside the component.
<div>
<div className="demo">test</div>
<style jsx>{`
.demo {
color: red;
}
`}
</style>
</div>
Copy the code
There is also the CSS module approach, which allows the CSS styles of components to be written in a separate CSS file by using the CSS module function. The CSS module convention style file name must be the name of the component file. Modules.css
index.module.css
.p {
color: green;
}
Copy the code
import styles from './index.module.css';
<div className={styles.p}>test</div>
Copy the code
- Global style file
Create _app.js in the pages folder. It must be called by this name and cannot be modified.
Then create the styles folder under the project root and create global.css in it. This name can be changed at will.
Then import global.css in _app.js via import, and add the following code to _app.js.
export default function App({ Component, pageProps}) {
return <Component {. pageProps} / >
}
Copy the code
global.css
body {
background: red;
}
Copy the code
Finally, restart the development server to take effect.
pre-rendered
Prerendering is the stitching of data and HTML on the server side ahead of time. Pre-rendering can make SEO much friendlier. Pre-rendering makes for a better user experience, allowing you to view your application’S UI without running JavaScript.
Two forms of pre-rendering are supported in next.js: static generation and server-side rendering. Static generation and server-side rendering differ in the timing of HTML generation.
Static generation: Static generation generates HTML at build time. Each subsequent request shares the HTML generated at build time.
Server-side rendering: Server-side rendering generates HTML on request. HTML is regenerated on each request.
Next. Js allows developers to choose a different pre-rendering method for each page. Different pre-rendering methods have different characteristics. Render according to the scene, but static generation is recommended for most pages.
Static generation of a build, repeated use, fast access. Because the pages are pre-generated.
Application scenario: marketing pages, blog posts, e-commerce product listings, help, and documentation.
Server-side rendering access is not as fast as static generation, but because it is rerendered on every request, it is suitable for pages where data is frequently updated or where page content changes with requests.
- Static generated
If the component doesn’t need to fetch data elsewhere, generate it statically.
If the component needs to fetch data elsewhere, at build time, next.js prefetches the data the component needs and then statically generates the component.
The getStaticProps method is used to get the data needed for static generation of the component. And pass the data to the component as props, which is an asynchronous function that needs to be exported inside the component. In development mode, getStaticProps runs on each request instead.
The getStaticProps method is run at build time, which means it is running on Node, so it can be written in Node syntax, and it can access files and databases.
import Head from 'next/head';
import styles from './list.moduls.css'
// Export an asynchronous function
export async function getStaticProps() {
// Get data from file system, API, database
const data = ...
// The value of the props property will be passed to the component
return {
props:...// The data returned}}export default function List(props) {
// props gets the props returned from getStaticProps
rteurn <>
<Head>
<title>Index Page</title>
</Head>
<div className={styles.demo}>test</div>< / a >}Copy the code
- Server side rendering
Server rendering is built without generating HTML and dynamically generates HTML back to the browser when the page is requested, using getServerSideProps.
In the same way, if you use server-side rendering, you need to export the getServerSideProps method in the component. The context in the method carries the parameters that the client requests.
export async function getServerSideProps(context) {
return {
props: {
data: context.query
}
}
}
export default function List(props) {
// props gets the props returned from getStaticProps
console.log(props);
rteurn <>
<Head>
<title>Index Page</title>
</Head>
<div className={styles.demo}>test</div>< / a >}Copy the code
- Static rendering based on dynamic routing
Generate HTML pages for page components based on parameters, and generate as many HTML pages as there are parameters. In application construction, obtain all routing parameters accessible to users, then obtain specific data according to routing parameters, and then generate static HTML according to the data.
Create a page component file based on dynamic routing and name it with [], such as [id].js. I’m going to call it id so the value of params in the return value is going to be called ID
Export the asynchronous function getStaticPaths to get route parameters accessible to all users.
export async function getStaticPaths() {
// Get the route parameters accessible to all users
// The value of the props property will be passed to the component
return {
// Return route parameters in fixed format
paths: [{params: {id: 1}}, {params: {id: 2}}].// Whether to display 404 when the user access route parameter is not returned in the current function. False indicates that 404 is displayed; true indicates that 404 is not displayed
fallback: false}}Copy the code
If fallback is set to true, a wait state is required for the page, otherwise the build will fail.
// Determine whether the server is performing static generation
import { useRouter } from 'next/router';
export default function List(props) {
const router = useRouter();
// If the value is true, it is being generated statically
if (router.isFallback) {
return <div>loading</div>
}
rteurn <>
<Head>
<title>Index Page</title>
</Head>
<div className={styles.demo}>test</div>< / a >}Copy the code
Finally, the asynchronous function getStaticProps is exported to get specific data based on routing parameters.
GetStaticPaths and getStaticProps run only on the server side, never on the client side, and are not even packaged into client-side JavaScript, which means you can write server-side code as you please, such as querying databases.
export async function getStaticProps({params}) {
// params => id: 1
// Obtain specific data based on route parameters
return {
// Pass the data to the component for static page generation
props: {}}}Copy the code
- Customize 404 pages
To create a custom 404 page, create a 404.js file in the Pages folder.
export default function Custom404() {
return <h1>404</h1>
}
Copy the code
API Routes
API Routes Interface used by the client to send data requests to the server.
The Next. Js app allows React developers to write server-side code to create data interfaces.
Create an API Routes file in the Pages/API folder. Such as user. Js
The request handler function is exported in the file by default. The function takes two parameters, req for the request object and res for the response object.
Current API Routes can receive any Http request method.
export default function(req, res) {
res.status(200).send({id: 1.name: 'yd'})}Copy the code
Do not access API Routes in the getStaticPaths or getStaticProps functions, because these functions run on the server side and you can write server-side code directly.
API Routes can be understood as the middle layer agent. We send the request for the service to the node middle layer. The middle layer then requests the service and returns the request to the front end.
localhost:3000/api/user
{
id: 1.name: 'yd'
}
Copy the code