instruction
stringlengths 31
302
| output
stringlengths 22
4.36k
| source_url
stringlengths 41
99
|
---|---|---|
How do I implement Fallback pages in Next.js? | In the “fallback” version of a page:
The page’s props will be empty.
Using the router, you can detect if the fallback is being rendered, router.isFallback will be true.
The following example showcases using isFallback:
```jsx
import { useRouter } from 'next/router'
function Post({ post }) {
const router = useRouter()
// If the page is not yet generated, this will be displayed
// initially until getStaticProps() finishes running
if (router.isFallback) {
return <div>Loading...</div>
}
// Render post...
}
// This function gets called at build time
export async function getStaticPaths() {
return {
// Only `/posts/1` and `/posts/2` are generated at build time
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
// Enable statically generating additional pages
// For example: `/posts/3`
fallback: true,
}
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return {
props: { post },
// Re-generate the post at most once per second
// if a request comes in
revalidate: 1,
}
}
export default Post
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/api-reference/functions/get-static-paths |
How do I implement in Next.js? | AMP support is one of our advanced features, you can read more about AMP here.
To enable AMP, add the following config to your page:
The amp config accepts the following values:
true - The page will be AMP-only
'hybrid' - The page will have two versions, one with AMP and another one with HTML
To learn more about the amp config, read the sections below.
```javascript
export const config = { amp: true }
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/api-reference/functions/use-amp |
How do I implement AMP First Page in Next.js? | Take a look at the following example:
The page above is an AMP-only page, which means:
```javascript
export const config = { amp: true }
function About(props) {
return <h3>My AMP About Page!</h3>
}
export default About
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/api-reference/functions/use-amp |
How do I implement Hybrid AMP Page in Next.js? | Take a look at the following example:
The page above is a hybrid AMP page, which means:
The page is rendered as traditional HTML (default) and AMP HTML (by adding ?amp=1 to the URL)
The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines
The page uses useAmp to differentiate between modes, it's a React Hook that returns true if the page is using AMP, and false otherwise.
Was this helpful?
```javascript
import { useAmp } from 'next/amp'
export const config = { amp: 'hybrid' }
function About(props) {
const isAmp = useAmp()
return (
<div>
<h3>My AMP About Page!</h3>
{isAmp ? (
<amp-img
width="300"
height="300"
src="/my-img.jpg"
alt="a cool image"
layout="responsive"
/>
) : (
<img width="300" height="300" src="/my-img.jpg" alt="a cool image" />
)}
</div>
)
}
export default About
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/api-reference/functions/use-amp |
How do I implement in Next.js? | The useReportWebVitals hook allows you to report Core Web Vitals, and can be used in combination with your analytics service.
```javascript
import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
useReportWebVitals((metric) => {
console.log(metric)
})
return <Component {...pageProps} />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/api-reference/functions/use-report-web-vitals |
How do I implement Custom Metrics in Next.js? | In addition to the core metrics listed above, there are some additional custom metrics that
measure the time it takes for the page to hydrate and render:
You can handle all the results of these metrics separately:
These metrics work in all browsers that support the User Timing API.
```javascript
import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'Next.js-hydration':
// handle hydration results
break
case 'Next.js-route-change-to-render':
// handle route-change to render results
break
case 'Next.js-render':
// handle render results
break
default:
break
}
})
return <Component {...pageProps} />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/api-reference/functions/use-report-web-vitals |
How do I implement AMP in Static HTML Export in Next.js? | For example, the hybrid AMP page pages/about.js would output:
out/about.html - HTML page with client-side React runtime
out/about.amp.html - AMP page
And if pages/about.js is an AMP-only page, then it would output:
out/about.html - Optimized AMP page
And the AMP version of your page will include a link to the HTML page:
When trailingSlash is enabled the exported pages for pages/about.js would be:
out/about/index.html - HTML page
out/about.amp/index.html - AMP page
```jsx
<link rel="amphtml" href="/about.amp.html" />
```
```jsx
<link rel="canonical" href="/about" />
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/amp |
How do I implement Adding Presets and Plugins in Next.js? | Here's an example .babelrc file:
To add presets/plugins without configuring them, you can do it this way:
```json
{
"presets": ["next/babel"],
"plugins": []
}
```
```json
{
"presets": ["next/babel"],
"plugins": ["@babel/plugin-proposal-do-expressions"]
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/babel |
How do I implement Customizing Presets and Plugins in Next.js? | To learn more about the available options for each config, visit babel's documentation site.
Good to know:
Was this helpful?
```json
{
"presets": [
[
"next/babel",
{
"preset-env": {},
"transform-runtime": {},
"styled-jsx": {},
"class-properties": {}
}
]
],
"plugins": []
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/babel |
How do I implement C S in Next.js? | Good to know:
Take a look at the following example of a custom server:
To run the custom server, you'll need to update the scripts in package.json like so:
```jsx
import { createServer } from 'http'
import { parse } from 'url'
import next from 'next'
const port = parseInt(process.env.PORT || '3000', 10)
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
}).listen(port)
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? 'development' : process.env.NODE_ENV
}`
)
})
```
```json
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
```
```javascript
import next from 'next'
const app = next({})
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/custom-server |
How do I implement Disabling file-system routing in Next.js? | You may also wish to configure the client-side router to disallow client-side redirects to filename routes; for that refer to router.beforePopState.
Was this helpful?
```javascript
module.exports = {
useFileSystemPublicRoutes: false,
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/custom-server |
How do I implement Default Behavior in Next.js? | By default, CSS Grid and Custom Properties (CSS variables) are not compiled for IE11 support.
To compile CSS Grid Layout for IE11, you can place the following comment at the top of your CSS file:
You can also enable IE11 support for CSS Grid Layout
in your entire project by configuring autoprefixer with the configuration shown below (collapsed).
See "Customizing Plugins" below for more information.
CSS variables are not compiled because it is not possible to safely do so.
If you must use variables, consider using something like Sass variables which are compiled away by Sass.
```json
{
"plugins": [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
"autoprefixer": {
"flexbox": "no-2009",
"grid": "autoplace"
},
"stage": 3,
"features": {
"custom-properties": false
}
}
]
]
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/post-css |
How do I implement Customizing Target Browsers in Next.js? | To customize browserslist, create a browserslist key in your package.json like so:
You can use the browsersl.ist tool to visualize what browsers you are targeting.
```json
{
"browserslist": [">0.3%", "not dead", "not op_mini all"]
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/post-css |
How do I implement Customizing Plugins in Next.js? | To customize the PostCSS configuration, create a postcss.config.json file in the root of your project.
It is also possible to configure PostCSS with a postcss.config.js file, which is useful when you want to conditionally include plugins based on environment:
Do not use require() to import the PostCSS Plugins. Plugins must be provided as strings.
Was this helpful?
```jsx
{
"plugins": [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
"autoprefixer": {
"flexbox": "no-2009"
},
"stage": 3,
"features": {
"custom-properties": false
}
}
]
]
}
```
```javascript
module.exports = {
plugins:
process.env.NODE_ENV === 'production'
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
features: {
'custom-properties': false,
},
},
],
]
: [
// No transformations in development
],
}
```
```css
module.exports = {
plugins: {
'postcss-flexbugs-fixes': {},
'postcss-preset-env': {
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
features: {
'custom-properties': false,
},
},
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/configuring/post-css |
How do I implement Client-side data fetching with useEffect in Next.js? | The following example shows how you can fetch data on the client side using the useEffect hook.
```jsx
import { useState, useEffect } from 'react'
function Profile() {
const [data, setData] = useState(null)
const [isLoading, setLoading] = useState(true)
useEffect(() => {
fetch('/api/profile-data')
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
}, [])
if (isLoading) return <p>Loading...</p>
if (!data) return <p>No profile data</p>
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side |
How do I implement Example in Next.js? | You can use getServerSideProps by exporting it from a Page Component. The example below shows how you can fetch data from a 3rd party API in getServerSideProps, and pass the data to the page as props:
```jsx
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
// Pass data to the page via props
return { props: { repo } }
}
export default function Page({ repo }) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props |
How do I implement Caching with Server-Side Rendering (SSR) in Next.js? | You can use caching headers (Cache-Control) inside getServerSideProps to cache dynamic responses. For example, using stale-while-revalidate.
However, before reaching for cache-control, we recommend seeing if getStaticProps with ISR is a better fit for your use case.
Was this helpful?
```typescript
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props |
How do I implement in Next.js? | If a page has Dynamic Routes and uses getStaticProps, it needs to define a list of paths to be statically generated.
The getStaticPaths API reference covers all parameters and props that can be used with getStaticPaths.
```jsx
export async function getStaticPaths() {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // See the "paths" section below
],
fallback: true, // false or "blocking"
}
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}
export default function Page({ repo }) {
return repo.stargazers_count
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-paths |
How do I implement Generating paths on-demand in Next.js? | getStaticPaths allows you to control which pages are generated during the build instead of on-demand with fallback. Generating more pages during a build will cause slower builds.
Was this helpful?
```typescript
export async function getStaticPaths() {
// When this is true (in preview environments) don't
// prerender any static pages
// (faster builds, but slower initial page load)
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
}
}
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to prerender based on posts
// In production environments, prerender all pages
// (slower builds, but faster initial page load)
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// { fallback: false } means other routes should 404
return { paths, fallback: false }
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-paths |
How do I implement in Next.js? | Note that irrespective of rendering type, any props will be passed to the page component and can be viewed on the client-side in the initial HTML. This is to allow the page to be hydrated correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in props.
The getStaticProps API reference covers all parameters and props that can be used with getStaticProps.
```jsx
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}
export default function Page({ repo }) {
return repo.stargazers_count
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props |
How do I implement Using getStaticProps to fetch data from a CMS in Next.js? | The following example shows how you can fetch a list of blog posts from a CMS.
The getStaticProps API reference covers all parameters and props that can be used with getStaticProps.
```jsx
// posts will be populated at build time by getStaticProps()
export default function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props |
How do I implement Write server-side code directly in Next.js? | As getStaticProps runs only on the server-side, it will never run on the client-side. It won’t even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers.
This means that instead of fetching an API route from getStaticProps (that itself fetches data from an external source), you can write the server-side code directly in getStaticProps.
Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from getStaticProps. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be shared by using a lib/ directory. Then it can be shared with getStaticProps.
Alternatively, if you are not using API routes to fetch data, then the fetch() API can be used directly in getStaticProps to fetch data.
```javascript
// The following function is shared
// with getStaticProps and API routes
// from a `lib/` directory
export async function loadPosts() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts/')
const data = await res.json()
return data
}
```
```javascript
// pages/blog.js
import { loadPosts } from '../lib/load-posts'
// This function runs only on the server side
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
const posts = await loadPosts()
// Props returned will be passed to the page component
return { props: { posts } }
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props |
How do I implement Configuration in Next.js? | You can utilize getStaticProps and getStaticPaths to generate an HTML file for each page in your pages directory (or more for dynamic routes).
```javascript
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
output: 'export',
// Optional: Change links `/me` -> `/me/` and emit `/me.html` -> `/me/index.html`
// trailingSlash: true,
// Optional: Prevent automatic `/me` -> `/me/`, instead preserve `href`
// skipTrailingSlashRedirect: true,
// Optional: Change the output directory `out` -> `dist`
// distDir: 'dist',
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/deploying/static-exports |
How do I implement Google Fonts in Next.js? | Automatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment. No requests are sent to Google by the browser.
To use the font in all your pages, add it to _app.js file under /pages as shown below:
If you can't use a variable font, you will need to specify a weight:
```javascript
import { Inter } from 'next/font/google'
// If loading a variable font, you don't need to specify the font weight
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
<main className={inter.className}>
<Component {...pageProps} />
</main>
)
}
```
```javascript
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={roboto.className}>
<Component {...pageProps} />
</main>
)
}
```
```javascript
const roboto = Roboto({
weight: ['400', '700'],
style: ['normal', 'italic'],
subsets: ['latin'],
display: 'swap',
})
```
## Best Practices
- You can specify multiple weights and/or styles by using an array:
- Good to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono.
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/fonts |
How do I implement Apply the font in <head> in Next.js? | You can also use the font without a wrapper and className by injecting it inside the <head> as follows:
```javascript
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
<>
<style jsx global>{`
html {
font-family: ${inter.style.fontFamily};
}
`}</style>
<Component {...pageProps} />
</>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/fonts |
How do I implement Single page usage in Next.js? | To use the font on a single page, add it to the specific page as shown below:
```javascript
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function Home() {
return (
<div className={inter.className}>
<p>Hello World</p>
</div>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/fonts |
How do I implement With named exports in Next.js? | To dynamically import a named export, you can return it from the Promise returned by import():
```javascript
export function Hello() {
return <p>Hello!</p>
}
// pages/index.js
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() =>
import('../components/hello').then((mod) => mod.Hello)
)
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading |
How do I implement With no SSR in Next.js? | To dynamically load a component on the client side, you can use the ssr option to disable server-rendering. This is useful if an external dependency or component relies on browser APIs like window.
```jsx
'use client'
import dynamic from 'next/dynamic'
const DynamicHeader = dynamic(() => import('../components/header'), {
ssr: false,
})
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading |
How do I implement With external libraries in Next.js? | This example uses the external library fuse.js for fuzzy search. The module is only loaded in the browser after the user types in the search input.
Was this helpful?
```jsx
import { useState } from 'react'
const names = ['Tim', 'Joe', 'Bel', 'Lee']
export default function Page() {
const [results, setResults] = useState()
return (
<div>
<input
type="text"
placeholder="Search"
onChange={async (e) => {
const { value } = e.currentTarget
// Dynamically load fuse.js
const Fuse = (await import('fuse.js')).default
const fuse = new Fuse(names)
setResults(fuse.search(value))
}}
/>
<pre>Results: {JSON.stringify(results, null, 2)}</pre>
</div>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading |
How do I implement Additional Attributes in Next.js? | There are many DOM attributes that can be assigned to a <script> element that are not used by the Script component, like nonce or custom data attributes. Including any additional attributes will automatically forward it to the final, optimized <script> element that is included in the HTML.
Was this helpful?
```javascript
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://example.com/script.js"
id="example-script"
nonce="XUENAJFW"
data-test="script"
/>
</>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/scripts |
How do I implement S A in Next.js? | For example, the file public/avatars/me.png can be viewed by visiting the /avatars/me.png path. The code to display that image might look like:
```javascript
import Image from 'next/image'
export function Avatar({ id, alt }) {
return <Image src={`/avatars/${id}.png`} alt={alt} width="64" height="64" />
}
export function AvatarOfMe() {
return <Avatar id="me" alt="A portrait of me" />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/static-assets |
How do I implement Google Tag Manager in Next.js? | The GoogleTagManager component can be used to instantiate a Google Tag Manager container to your page. By default, it fetches the original inline script after hydration occurs on the page.
To load Google Tag Manager for all routes, include the component directly in your custom _app and
pass in your GTM container ID:
To load Google Tag Manager for a single route, include the component in your page file:
```javascript
import { GoogleTagManager } from '@next/third-parties/google'
export default function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<GoogleTagManager gtmId="GTM-XYZ" />
</>
)
}
```
```javascript
import { GoogleTagManager } from '@next/third-parties/google'
export default function Page() {
return <GoogleTagManager gtmId="GTM-XYZ" />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/third-party-libraries |
How do I implement Google Analytics in Next.js? | The GoogleAnalytics component can be used to include Google Analytics
4 to your page via the Google tag
(gtag.js). By default, it fetches the original scripts after hydration occurs on the page.
Recommendation: If Google Tag Manager is already included in your application, you can
configure Google Analytics directly using it, rather than including Google Analytics as a separate
component. Refer to the
documentation
to learn more about the differences between Tag Manager and gtag.js.
To load Google Analytics for all routes, include the component directly in your custom _app and
pass in your measurement ID:
To load Google Analytics for a single route, include the component in your page file:
```javascript
import { GoogleAnalytics } from '@next/third-parties/google'
export default function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<GoogleAnalytics gaId="G-XYZ" />
</>
)
}
```
```javascript
import { GoogleAnalytics } from '@next/third-parties/google'
export default function Page() {
return <GoogleAnalytics gaId="G-XYZ" />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/optimizing/third-party-libraries |
What are the best practices for C-side R (CSR) in Next.js? |
## Best Practices
- Using React's useEffect() hook inside your pages instead of the server-side rendering methods (getStaticProps and getServerSideProps).
Using a data fetching library like SWR or TanStack Query to fetch data on the client (recommended).
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/rendering/client-side-rendering |
How do I implement S-side R (SSR) in Next.js? | Also referred to as "SSR" or "Dynamic Rendering".
If a page uses Server-side Rendering, the page HTML is generated on each request.
To use Server-side Rendering for a page, you need to export an async function called getServerSideProps. This function will be called by the server on every request.
For example, suppose that your page needs to pre-render frequently updated data (fetched from an external API). You can write getServerSideProps which fetches this data and passes it to Page like below:
As you can see, getServerSideProps is similar to getStaticProps, but the difference is that getServerSideProps is run on every request instead of on build time.
To learn more about how getServerSideProps works, check out our Data Fetching documentation.
Was this helpful?
```jsx
export default function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering |
How do I implement Scenario 1: Your page content depends on external data in Next.js? | Example: Your blog page might need to fetch the list of blog posts from a CMS (content management system).
To learn more about how getStaticProps works, check out the Data Fetching documentation.
```jsx
// TODO: Need to fetch `posts` (by calling some API endpoint)
// before this page can be pre-rendered.
export default function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
```
```jsx
export default function Blog({ posts }) {
// Render posts...
}
// This function gets called at build time
export async function getStaticProps() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation |
How do I implement Scenario 2: Your page paths depend on external data in Next.js? | To learn more about dynamic routing, check the Dynamic Routing documentation.
However, which id you want to pre-render at build time might depend on external data.
Example: suppose that you've only added one blog post (with id: 1) to the database. In this case, you'd only want to pre-render posts/1 at build time.
Later, you might add the second post with id: 2. Then you'd want to pre-render posts/2 as well.
Also in pages/posts/[id].js, you need to export getStaticProps so that you can fetch the data about the post with this id and use it to pre-render the page:
To learn more about how getStaticPaths works, check out the Data Fetching documentation.
```typescript
// This function gets called at build time
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false }
}
```
```jsx
export default function Post({ post }) {
// Render post...
}
export async function getStaticPaths() {
// ...
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return { props: { post } }
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation |
How do I implement Usage in Next.js? | To override the default App, create the file pages/_app as shown below:
The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page.
pageProps is an object with the initial props that were preloaded for your page by one of our data fetching methods, otherwise it's an empty object.
Good to know:
```jsx
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/custom-app |
How do I implement getInitialProps with App in Next.js? | Using getInitialProps in App will disable Automatic Static Optimization for pages without getStaticProps.
We do not recommend using this pattern. Instead, consider incrementally adopting the App Router, which allows you to more easily fetch data for pages and layouts.
Was this helpful?
```jsx
import App from 'next/app'
export default function MyApp({ Component, pageProps, example }) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}
MyApp.getInitialProps = async (context) => {
const ctx = await App.getInitialProps(context)
return { ...ctx, example: 'data' }
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/custom-app |
How do I implement C D in Next.js? | A custom Document can update the <html> and <body> tags used to render a Page.
To override the default Document, create the file pages/_document as shown below:
Good to know:
```javascript
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/custom-document |
How do I implement Customizing renderPage in Next.js? | Customizing renderPage is advanced and only needed for libraries like CSS-in-JS to support server-side rendering. This is not needed for built-in styled-jsx support.
We do not recommend using this pattern. Instead, consider incrementally adopting the App Router, which allows you to more easily fetch data for pages and layouts.
Good to know:
getInitialProps in _document is not called during client-side transitions.
The ctx object for _document is equivalent to the one received in getInitialProps, with the addition of renderPage.
Was this helpful?
```typescript
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const originalRenderPage = ctx.renderPage
// Run the React rendering logic synchronously
ctx.renderPage = () =>
originalRenderPage({
// Useful for wrapping the whole react tree
enhanceApp: (App) => App,
// Useful for wrapping in a per-page basis
enhanceComponent: (Component) => Component,
})
// Run the parent `getInitialProps`, it now includes the custom `renderPage`
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/custom-document |
How do I implement Customizing The 404 Page in Next.js? | To create a custom 404 page you can create a pages/404.js file. This file is statically generated at build time.
Good to know: You can use getStaticProps inside this page if you need to fetch data at build time.
```javascript
export default function Custom404() {
return <h1>404 - Page Not Found</h1>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/custom-error |
How do I implement Example in Next.js? | For example, a blog could include the following route pages/blog/[slug].js where [slug] is the Dynamic Segment for blog posts.
```jsx
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return <p>Post: {router.query.slug}</p>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes |
How do I implement L and N in Next.js? | A React component called Link is provided to do this client-side route transition.
/ → pages/index.js
/about → pages/about.js
/blog/hello-world → pages/blog/[slug].js
Any <Link /> in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using Static Generation. The corresponding data for server-rendered routes is fetched only when the <Link /> is clicked.
```html
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/about">About Us</Link>
</li>
<li>
<Link href="/blog/hello-world">Blog Post</Link>
</li>
</ul>
)
}
export default Home
```
## Best Practices
- The example above uses multiple links. Each one maps a path (href) to a known page:
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating |
What are the best practices for L and N in Next.js? |
```html
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/about">About Us</Link>
</li>
<li>
<Link href="/blog/hello-world">Blog Post</Link>
</li>
</ul>
)
}
export default Home
```
## Best Practices
- The example above uses multiple links. Each one maps a path (href) to a known page:
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating |
How do I implement Linking to dynamic paths in Next.js? | You can also use interpolation to create the path, which comes in handy for dynamic route segments. For example, to show a list of posts which have been passed to the component as a prop:
encodeURIComponent is used in the example to keep the path utf-8 compatible.
Alternatively, using a URL Object:
Now, instead of using interpolation to create the path, we use a URL object in href where:
pathname is the name of the page in the pages directory. /blog/[slug] in this case.
query is an object with the dynamic segment. slug in this case.
```jsx
import Link from 'next/link'
function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/blog/${encodeURIComponent(post.slug)}`}>
{post.title}
</Link>
</li>
))}
</ul>
)
}
export default Posts
```
```jsx
import Link from 'next/link'
function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link
href={{
pathname: '/blog/[slug]',
query: { slug: post.slug },
}}
>
{post.title}
</Link>
</li>
))}
</ul>
)
}
export default Posts
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating |
How do I implement Shallow Routing in Next.js? | Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.
You'll receive the updated pathname and the query via the router object (added by useRouter or withRouter), without losing state.
To enable shallow routing, set the shallow option to true. Consider the following example:
The URL will get updated to /?counter=10 and the page won't get replaced, only the state of the route is changed.
You can also watch for URL changes via componentDidUpdate as shown below:
```jsx
import { useEffect } from 'react'
import { useRouter } from 'next/router'
// Current URL is '/'
function Page() {
const router = useRouter()
useEffect(() => {
// Always do navigations after the first render
router.push('/?counter=10', undefined, { shallow: true })
}, [])
useEffect(() => {
// The counter changed!
}, [router.query.counter])
}
export default Page
```
```jsx
componentDidUpdate(prevProps) {
const { pathname, query } = this.props.router
// verify props have changed to avoid an infinite loop
if (query.counter !== prevProps.router.query.counter) {
// fetch data based on the new query
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating |
How do I implement Pages and L in Next.js? | The Pages Router has a file-system based router built on the concept of pages.
When a file is added to the pages directory, it's automatically available as a route.
Example: If you create pages/about.js that exports a React component like below, it will be accessible at /about.
```html
export default function About() {
return <div>About</div>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts |
How do I implement Single Shared Layout with Custom App in Next.js? | If you only have one layout for your entire application, you can create a Custom App and wrap your application with the layout. Since the <Layout /> component is re-used when changing pages, its component state will be preserved (e.g. input values).
```javascript
import Layout from '../components/layout'
export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts |
How do I implement Per-Page Layouts in Next.js? | When navigating between pages, we want to persist page state (input values, scroll position, etc.) for a Single-Page Application (SPA) experience.
This layout pattern enables state persistence because the React component tree is maintained between page transitions. With the component tree, React can understand which elements have changed to preserve state.
Good to know: This process is called reconciliation, which is how React understands which elements have changed.
```javascript
import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'
export default function Page() {
return (
/** Your content */
)
}
Page.getLayout = function getLayout(page) {
return (
<Layout>
<NestedLayout>{page}</NestedLayout>
</Layout>
)
}
```
```javascript
export default function MyApp({ Component, pageProps }) {
// Use the layout defined at the page level, if available
const getLayout = Component.getLayout ?? ((page) => page)
return getLayout(<Component {...pageProps} />)
}
```
## Best Practices
- If you need multiple layouts, you can add a property getLayout to your page, allowing you to return a React component for the layout. This allows you to define the layout on a per-page basis. Since we're returning a function, we can have complex nested layouts if desired.
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts |
What are the best practices for Per-Page Layouts in Next.js? |
```javascript
import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'
export default function Page() {
return (
/** Your content */
)
}
Page.getLayout = function getLayout(page) {
return (
<Layout>
<NestedLayout>{page}</NestedLayout>
</Layout>
)
}
```
```javascript
export default function MyApp({ Component, pageProps }) {
// Use the layout defined at the page level, if available
const getLayout = Component.getLayout ?? ((page) => page)
return getLayout(<Component {...pageProps} />)
}
```
## Best Practices
- If you need multiple layouts, you can add a property getLayout to your page, allowing you to return a React component for the layout. This allows you to define the layout on a per-page basis. Since we're returning a function, we can have complex nested layouts if desired.
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts |
How do I implement useRouter() hook in Next.js? | If you need to redirect inside a component, you can use the push method from the useRouter hook. For example:
Good to know:
If you don't need to programmatically navigate a user, you should use a <Link> component.
See the useRouter API reference for more information.
```jsx
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/redirecting |
How do I implement 2. Optimizing data lookup performance in Next.js? | Reading a large dataset for every incoming request can be slow and expensive. There are two ways you can optimize data lookup performance:
Use a database that is optimized for fast reads, such as Vercel Edge Config or Redis.
Use a data lookup strategy such as a Bloom filter to efficiently check if a redirect exists before reading the larger redirects file or database.
If it does, forward the request to a API Routes which will check the actual file and redirect the user to the appropriate URL. This avoids importing a large redirects file into Middleware, which can slow down every incoming request.
Then, in the API Route:
Good to know:
To generate a bloom filter, you can use a library like bloom-filters.
You should validate requests made to your Route Handler to prevent malicious requests.
Was this helpful?
```typescript
import redirects from '@/app/redirects/redirects.json'
export default function handler(req, res) {
const pathname = req.query.pathname
if (!pathname) {
return res.status(400).json({ message: 'Bad Request' })
}
// Get the redirect entry from the redirects.json file
const redirect = redirects[pathname]
// Account for bloom filter false positives
if (!redirect) {
return res.status(400).json({ message: 'No redirect' })
}
// Return the redirect entry
return res.json(redirect)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/routing/redirecting |
How do I implement Global Styles in Next.js? | To add a stylesheet to your application, import the CSS file within pages/_app.js.
For example, consider the following stylesheet named styles.css:
Create a pages/_app.js file if not already present.
Then, import the styles.css file.
These styles (styles.css) will apply to all pages and components in your application.
Due to the global nature of stylesheets, and to avoid conflicts, you may only import them inside pages/_app.js.
In development, expressing stylesheets this way allows your styles to be hot reloaded as you edit them—meaning you can keep application state.
In production, all CSS files will be automatically concatenated into a single minified .css file. The order that the CSS is concatenated will match the order the CSS is imported into the _app.js file. Pay special attention to imported JS modules that include their own CSS; the JS module's CSS will be concatenated following the same ordering rules as imported CSS files. For example:
```javascript
import '../styles.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/styling/css |
How do I implement Import styles from node_modules in Next.js? | For global stylesheets, like bootstrap or nprogress, you should import the file inside pages/_app.js.
For example:
For importing CSS required by a third-party component, you can do so in your component. For example:
```javascript
import 'bootstrap/dist/css/bootstrap.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
```javascript
import { useState } from 'react'
import { Dialog } from '@reach/dialog'
import VisuallyHidden from '@reach/visually-hidden'
import '@reach/dialog/styles.css'
function ExampleDialog(props) {
const [showDialog, setShowDialog] = useState(false)
const open = () => setShowDialog(true)
const close = () => setShowDialog(false)
return (
<div>
<button onClick={open}>Open Dialog</button>
<Dialog isOpen={showDialog} onDismiss={close}>
<button className="close-button" onClick={close}>
<VisuallyHidden>Close</VisuallyHidden>
<span aria-hidden>×</span>
</button>
<p>Hello there. I am a dialog</p>
</Dialog>
</div>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/styling/css |
How do I implement CSS-in-JS in Next.js? | We bundle styled-jsx to provide support for isolated scoped CSS.
The aim is to support "shadow CSS" similar to Web Components, which unfortunately do not support server-rendering and are JS-only.
A component using styled-jsx looks like this:
Please see the styled-jsx documentation for more examples.
```jsx
function HiThere() {
return <p style={{ color: 'red' }}>hi there</p>
}
export default HiThere
```
```html
function HelloWorld() {
return (
<div>
Hello world
<p>scoped!</p>
<style jsx>{`
p {
color: blue;
}
div {
background: red;
}
@media (max-width: 600px) {
div {
background: blue;
}
}
`}</style>
<style global jsx>{`
body {
background: black;
}
`}</style>
</div>
)
}
export default HelloWorld
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/styling/css-in-js |
How do I implement Importing Styles in Next.js? | Add the Tailwind CSS directives that Tailwind will use to inject its generated styles to a Global Stylesheet in your application, for example:
Inside the custom app file (pages/_app.js), import the globals.css stylesheet to apply the styles to every route in your application.
```jsx
// These styles apply to every route in the application
import '@/styles/globals.css'
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/styling/tailwind-css |
How do I implement Creating your first Vitest Unit Test in Next.js? | Check that everything is working by creating a test to check if the <Page /> component successfully renders a heading:
```html
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
```
```typescript
import { expect, test } from 'vitest'
import { render, screen } from '@testing-library/react'
import Page from '../pages/index'
test('Page', () => {
render(<Page />)
expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined()
})
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/testing/vitest |
How do I implement V 10 in Next.js? | There were no breaking changes between versions 9 and 10.
To upgrade to version 10, run the following command:
Good to know: If you are using TypeScript, ensure you also upgrade @types/react and @types/react-dom to their corresponding versions.
Was this helpful?
```bash
npm i next@10
```
```bash
yarn add next@10
```
```bash
pnpm up next@10
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-10 |
How do I implement V 11 in Next.js? | To upgrade to version 11, run the following command:
Good to know: If you are using TypeScript, ensure you also upgrade @types/react and @types/react-dom to their corresponding versions.
```bash
npm i next@11 react@17 react-dom@17
```
```bash
yarn add next@11 react@17 react-dom@17
```
```bash
pnpm up next@11 react@17 react-dom@17
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-11 |
How do I implement Update usage of router.events in Next.js? | If your application uses router.router.events which was an internal property that was not public please make sure to use router.events as well.
```jsx
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
console.log(
`App is changing to ${url} ${
shallow ? 'with' : 'without'
} shallow routing`
)
}
router.events.on('routeChangeStart', handleRouteChange)
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeStart', handleRouteChange)
}
}, [router])
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-11 |
How do I implement React 16 to 17 in Next.js? | To upgrade you can run the following command:
Or using yarn:
Was this helpful?
```bash
npm install react@latest react-dom@latest
```
```bash
yarn add react@latest react-dom@latest
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-11 |
How do I implement V 12 in Next.js? | To upgrade to version 12, run the following command:
Good to know: If you are using TypeScript, ensure you also upgrade @types/react and @types/react-dom to their corresponding versions.
```bash
npm i next@12 react@17 react-dom@17 eslint-config-next@12
```
```bash
yarn add next@12 react@17 react-dom@17 eslint-config-next@12
```
```bash
pnpm up next@12 react@17 react-dom@17 eslint-config-next@12
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-12 |
How do I implement Upgrading to 12.0 in Next.js? | Minimum Node.js Version - The minimum Node.js version has been bumped from 12.0.0 to 12.22.0 which is the first version of Node.js with native ES Modules support.
Minimum React Version - The minimum required React version is 17.0.2. To upgrade you can run the following command in the terminal:
```bash
npm install react@latest react-dom@latest
yarn add react@latest react-dom@latest
pnpm update react@latest react-dom@latest
bun add react@latest react-dom@latest
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-12 |
How do I implement HMR connection now uses a WebSocket in Next.js? | If you are using Apache (2.x), you can add the following configuration to enable web sockets to the server. Review the port, host name and server names.
For custom servers, such as express, you may need to use app.all to ensure the request is passed correctly, for example:
```css
location /_next/webpack-hmr {
proxy_pass http://localhost:3000/_next/webpack-hmr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
```
```jsx
<VirtualHost *:443>
# ServerName yourwebsite.local
ServerName "${WEBSITE_SERVER_NAME}"
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
# Next.js 12 uses websocket
<Location /_next/webpack-hmr>
RewriteEngine On
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteCond %{HTTP:Connection} upgrade [NC]
RewriteRule /(.*) ws://localhost:3000/_next/webpack-hmr/$1 [P,L]
ProxyPass ws://localhost:3000/_next/webpack-hmr retry=0 timeout=30
ProxyPassReverse ws://localhost:3000/_next/webpack-hmr
</Location>
</VirtualHost>
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-12 |
How do I implement Upgrading from 12 to 13 in Next.js? | Good to know: If you are using TypeScript, ensure you also upgrade @types/react and @types/react-dom to their latest versions.
```bash
npm i next@13 react@latest react-dom@latest eslint-config-next@13
```
```bash
yarn add next@13 react@latest react-dom@latest eslint-config-next@13
```
```bash
pnpm i next@13 react@latest react-dom@latest eslint-config-next@13
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-13 |
What are the best practices for <Image/> Component in Next.js? |
## Best Practices
- Alternatively, you can manually update by following the migration guide and also see the legacy comparison.
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-13 |
How do I implement U to V 9 in Next.js? | To upgrade to version 9, run the following command:
Good to know: If you are using TypeScript, ensure you also upgrade @types/react and @types/react-dom to their corresponding versions.
```bash
npm i next@9
```
```bash
yarn add next@9
```
```bash
pnpm up next@9
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-9 |
How do I implement @zeit/next-typescript is no longer necessary in Next.js? | The following types are different:
This list was created by the community to help you upgrade, if you find other differences please send a pull-request to this list to help other users.
From:
to
```jsx
import { NextContext } from 'next'
import { NextAppContext, DefaultAppIProps } from 'next/app'
import { NextDocumentContext, DefaultDocumentIProps } from 'next/document'
```
```jsx
import { NextPageContext } from 'next'
import { AppContext, AppInitialProps } from 'next/app'
import { DocumentContext, DocumentInitialProps } from 'next/document'
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-9 |
How do I implement next/dynamic no longer renders "loading..." by default while loading in Next.js? | Dynamic components will not render anything by default while loading. You can still customize this behavior by setting the loading property:
```jsx
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello2'),
{
loading: () => <p>Loading</p>,
}
)
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-9 |
How do I implement withAmp has been removed in favor of an exported configuration object in Next.js? | To perform this migration by hand, or view what the codemod will produce, see below:
Before
After
```jsx
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export default withAmp(Home)
// or
export default withAmp(Home, { hybrid: true })
```
```typescript
export default function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
amp: true,
// or
amp: 'hybrid',
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-9 |
How do I implement next/dynamic has deprecated loading multiple modules at once in Next.js? | Updating code that relies on this behavior is relatively straightforward! We've provided an example of a before/after to help you migrate your application:
Before
After
Was this helpful?
```jsx
import dynamic from 'next/dynamic'
const HelloBundle = dynamic({
modules: () => {
const components = {
Hello1: () => import('../components/hello1').then((m) => m.default),
Hello2: () => import('../components/hello2').then((m) => m.default),
}
return components
},
render: (props, { Hello1, Hello2 }) => (
<div>
<h1>{props.title}</h1>
<Hello1 />
<Hello2 />
</div>
),
})
function DynamicBundle() {
return <HelloBundle title="Dynamic Bundle" />
}
export default DynamicBundle
```
```jsx
import dynamic from 'next/dynamic'
const Hello1 = dynamic(() => import('../components/hello1'))
const Hello2 = dynamic(() => import('../components/hello2'))
function HelloBundle({ title }) {
return (
<div>
<h1>{title}</h1>
<Hello1 />
<Hello2 />
</div>
)
}
function DynamicBundle() {
return <HelloBundle title="Dynamic Bundle" />
}
export default DynamicBundle
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/building-your-application/upgrading/version-9 |
How do I implement Create the pages directory in Next.js? | Finally, add a _document.tsx file inside pages/ to control the initial response from the server. Learn more about the custom Document file.
```javascript
export default function Page() {
return <h1>Hello, Next.js!</h1>
}
```
```jsx
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
```javascript
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/pages/getting-started/installation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.