learning next js
Next is a React framework to build fast web apps.
Important to know:
-
a lot of the concepts in these guides are not Next specific but the guide explains them anyways assuming the reader is new to all these concepts (things like rendering concepts, server location...)
-
Looks like I was reading an old
/learn
section which.
There is a newAppRouter
that can use more React features like server side components. The old Next router is thePagesRouter
the old tutorial I am/was following focuses on the oldPagesRouter
page router
-
routes are standalone files
-
_apps.jsx sets a layout for everything, global styles.. master component that wrap everything.
affects client-side rendering. -
_document.tsx allows you to customize the HTML document that gets served to your users. Want to add custom meta tags, scripts, or even change the server-rendered markup?
this file affects server0side rendering. -
every component runs on the server and the client. no React server components.
-
client-side navigation is enabled with the
<Link>
component. also accepts props for better control over navigation behavior. (for links outside of my app use<a>
) -
built-in support for code splitting and prefetching.
-
global css is in
pages/_apps.js
. only from that file.
Page router vs App router
Pasarle a danny para que entienda App router: https://freedium.cfd/https://javascript.plainenglish.io/next-jss-new-app-vs-pages-router-a-detailed-comparison-46f846963af5
introduced in may this year.
migration guide
page:
app: more like sveltekit
app router every dir name defines the URL path.
- we can store more components in the path's dir, they won't affect routing.
- there are reserved some names for files that can be in each page's dir. They have particular functionality:
- page.js: is the rendered component when accessing the path in the brower.
- **loading.js
- template.js
- layout.js
- head.js
//layout.js
export default function LoginLayout({ children }) {
return <div className='login-area'>{children}</div>
}
// all it needs to do is render a child component, passed autmatically. the child is the page.js component.
layout nesting is supported.
any component in the app dir are now server components by default. this means we can't use client-side features like window object, event listeners or React hooks .
server components are good for hiding code and secrets, don't ship most dependencies, direct access to backend, fully integrate server actions.
client components are declared by stating use client
on top of the file.
server actions (experimental)
enable exection of server-side code based on events on the client
server actions need to be enabled in the config.
App router should become the standard way to build apps.
some features are bound to the Pages Router and, therefore, will not prevail
- getStaticProps
- getServerSideProps
- getStaticPaths
- Custom document component
- Custom app component
- next/head
both routes can be used alongside, Vercel even recommends keeping the pages router while migration, as to not break anything. you can use both (/app/ and /pages/
) and not have to migrate the entire app entirely.
- custom document and app components are replaced by root layout.
- SEO-focused next/head component is entirely redundant. The App router offers built-in support for metadata.
import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Hello World',
}
export default function Page() {
return <></>
}
- the functions
getStaticProps, getServerSideProps and getStaticPaths
can be replaced by the new server actions.
Features overview:
- An intuitive page-based routing system (with support for dynamic routes)
- Pre-rendering, both static generation (SSG) and server-side rendering (SSR) are supported on a per-page basis
- Automatic code splitting for faster page loads
- Client-side routing with optimized prefetching
- Built-in CSS and Sass support, and support for any CSS-in-JS library
- Development environment with Fast Refresh support
- API routes to build API endpoints with Serverless Functions
- Fully extendable
one the /learn/
tuto I will learn ab this feats:
- Styling: The different ways to style your application in Next.js.
- Optimizations: How to optimize images, links, and fonts.
- Routing: How to create nested layouts and pages using file-system routing.
- Data Fetching: How to set up a database on Vercel, and best practices for fetching and streaming.
- Search and Pagination: How to implement search and pagination using URL Search Params.
- Mutating Data: How to mutate data using React Server Actions, and revalidate the Next.js cache.
- Error Handling: How to handle general and
404
not found errors. - Form Validation and Accessibility: How to do server-side form validation and tips for improving accessibility.
- Authentication: How to add authentication to your application using
NextAuth.js
and Middleware. - Metadata: How to add metadata and prepare your application for social sharing.
developer experience
Next.js comes with built in Typescript, ESLint and hot reloading, and more
In production stage
Next.js optimizes code and makes it accessible. code is compiled, bundled, minified and code split. Next handles a los of the process
- Compiling: transforming jsx/tsx into browser compatible js.
- Minifying: remove spaces, indents and multiple lines. Decreases file size.
- Bundling: resolving dependencies and merging the files into a single file. this is to reduce the number of requests for files when a user visits a web page.
- Code splitting: splitting the app's bundle into smaller chunks required by each entry point. With the goal of improving the aps initial load time by only loading teh code required to run that page.
This splitting reflects the different URL / entry points of an app.
at first glance it looks redundant to bundle and then resplit the code but oh well, I am sure there is a significant performance improvement at the end of the process.
Build time is the name given to the series of steps that prepare your app code for prod. When you build, Next.js will transform your code into prod-optimized files ready to be deployed to servers and consumed by users. the files include:
- HTML for static generated pages.
- js for rendering pages on the server
- js code for making pages interactive on the client.
- CSS files.
Runtime refers to the period of time when your app runs in response to a user's requests, after your app has been built and deployed.
rendering
Next components
Nextjs custom components and Hooks
dynamic routes
The network
In Next.js your app code can be deployed to:
Origin servers
normal server. stores and runs the original version of your app.
When an origin server receives a request, it does computation b4 sending a response. The result of this computation can be moved to a CDN.
CDN servers
CDN store statis content in multiple locations around the world and are placed between the client and the origin server. When a new request comes in, the closes CDN location to hte user can respond with the cached result. This reduces the load on the origin. In Next, since prerendering can be done ahead of time, CDNs are suited to store the result.
Edge servers
generalized concept for the edge of the network, closest to the user.
CDNs can be considered edge bc they distribute static content at the edge.
edge servers are distributed to multiple locations around the world. But unlike CDNs some edge servers can run small snippets of code. This means both caching and code execution can be done at the Edge closer to the user.
By moving some work that was traditionally done client-side or server-side ht hte Edge, you can make your app more performant bc it reduces the amount of code sent to the client.
Static assets
images... robots.txt or any other static asset.
are stored in the top-level dir /public
files inside this dir can be referenced from the root of the app, similar to pages/
API routes
404 pages
To create a custom 404 page, create pages/404.js. This file is statically generated at build time.
// pages/404.js
export default function Custom404() {
return <h1>404 - Page Not Found</h1>;
}
Deploy - Going to production:
https://nextjs.org/docs/pages/building-your-application/deploying/production-checklist
-
Vercel. Benefits of deploying with it:
- static generated pages and assets (js, css, images, fonts, etc...) will automatically be served form the Vercel Edge Network.
- Pages that use Server-Side Rendering and API routes will automatically become isolated Serverless Functions. This allows page rendering and API requests to scale infinitely.
-
Develop, Preview, Ship (DPS) workflow
- when you create a new branch and create a PR, Vercel automatically deploys a preview
-
deploying on own hosting provider.
- on other host providers do
npm run build
->npm run start
. (additionally add port"start": "next start -p $PORT"
)
- on other host providers do
SEO
https://nextjs.org/learn-pages-router/seo/introduction-to-seo
Typescript integration
https://nextjs.org/docs/pages/building-your-application/configuring/typescript
- you can use the
GetStaticProps
,GetStaticPaths
, andGetServerSideProps
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next' export const getStaticProps = (async (context) => { // ...}) satisfies GetStaticProps
- API routes:
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}
- Custom APP:
If you have a customApp
, you can use the built-in typeAppProps
and change file name to./pages/_app.tsx
like so:
import type { AppProps } from 'next/app' export default function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} />}