Next js build html

Deploying

Congratulations! You’re here because you are ready to deploy your Next.js application. This page will show how to deploy either managed or self-hosted using the Next.js Build API.

Next.js Build API

next build generates an optimized version of your application for production. This standard output includes:

  • HTML files for pages using getStaticProps or Automatic Static Optimization
  • CSS files for global styles or for individually scoped styles
  • JavaScript for pre-rendering dynamic content from the Next.js server
  • JavaScript for interactivity on the client-side through React

This output is generated inside the .next folder:

  • .next/static/chunks/pages – Each JavaScript file inside this folder relates to the route with the same name. For example, .next/static/chunks/pages/about.js would be the JavaScript file loaded when viewing the /about route in your application
  • .next/static/media – Statically imported images from next/image are hashed and copied here
  • .next/static/css – Global CSS files for all pages in your application
  • .next/server/pages – The HTML and JavaScript entry points prerendered from the server. The .nft.json files are created when Output File Tracing is enabled and contain all the file paths that depend on a given page.
  • .next/server/chunks – Shared JavaScript chunks used in multiple places throughout your application
  • .next/cache – Output for the build cache and cached images, responses, and pages from the Next.js server. Using a cache helps decrease build times and improve performance of loading images
Читайте также:  Work manager android kotlin

All JavaScript code inside .next has been compiled and browser bundles have been minified to help achieve the best performance and support all modern browsers.

Managed Next.js with Vercel

is the fastest way to deploy your Next.js application with zero configuration.

When deploying to Vercel, the platform automatically detects Next.js

, runs next build , and optimizes the build output for you, including:

  • Persisting cached assets across deployments if unchanged
  • Immutable deployments with a unique URL for every commit
  • Pages are automatically statically optimized, if possible
  • Assets (JavaScript, CSS, images, fonts) are compressed and served from a Global Edge Network
  • API Routes are automatically optimized as isolated Serverless Functions that can scale infinitely
  • Middleware is automatically optimized as Edge Functions that have zero cold starts and boot instantly

In addition, Vercel provides features like:

  • Automatic performance monitoring with Next.js Speed Insights
  • Automatic HTTPS and SSL certificates
  • Automatic CI/CD (through GitHub, GitLab, Bitbucket, etc.)
  • Support for Environment Variables
  • Support for Custom Domains
  • Support for Image Optimization with next/image
  • Instant global deployments via git push

Self-Hosting

You can self-host Next.js with support for all features using Node.js or Docker. You can also do a Static HTML Export, which has some limitations.

Node.js Server

Next.js can be deployed to any hosting provider that supports Node.js. For example, AWS EC2

First, ensure your package.json has the «build» and «start» scripts:

 "scripts":  "dev": "next dev", "build": "next build", "start": "next start"  > >

Then, run npm run build to build your application. Finally, run npm run start to start the Node.js server. This server supports all features of Next.js.

If you are using next/image , consider adding sharp for more performant Image Optimization in your production environment by running npm install sharp in your project directory. On Linux platforms, sharp may require additional configuration

to prevent excessive memory usage.

Docker Image

Next.js can be deployed to any hosting provider that supports Docker

containers. You can use this approach when deploying to container orchestrators such as Kubernetes

, or when running inside a single node in any cloud provider.

  1. Install Docker on your machine
  2. Clone the with-docker example
  3. Build your container: docker build -t nextjs-docker .
  4. Run your container: docker run -p 3000:3000 nextjs-docker

If you need to use different Environment Variables across multiple environments, check out our with-docker-multi-env

Static HTML Export

If you’d like to do a static HTML export of your Next.js app, follow the directions on our Static HTML Export documentation.

Other Services

The following services support Next.js v12+ . Below, you’ll find examples or guides to deploy Next.js to each service.

Managed Server

Good to know: There are also managed platforms that allow you to use a Dockerfile as shown in the example above.

Static Only

The following services only support deploying Next.js using output: ‘export’ .

You can also manually deploy the output from output: ‘export’ to any static hosting provider, often through your CI/CD pipeline like GitHub Actions, Jenkins, AWS CodeBuild, Circle CI, Azure Pipelines, and more.

Serverless

Good to know: Not all serverless providers implement the Next.js Build API from next start . Please check with the provider to see what features are supported.

Automatic Updates

When you deploy your Next.js application, you want to see the latest version without needing to reload.

Next.js will automatically load the latest version of your application in the background when routing. For client-side navigations, next/link will temporarily function as a normal tag.

Good to know: If a new page (with an old version) has already been prefetched by next/link , Next.js will use the old version. Navigating to a page that has not been prefetched (and is not cached at the CDN level) will load the latest version.

Manual Graceful shutdowns

When self-hosting, you might want to run code when the server shuts down on SIGTERM or SIGINT signals.

You can set the env variable NEXT_MANUAL_SIG_HANDLE to true and then register a handler for that signal inside your _document.js file. You will need to register the env variable directly in the package.json script, not in the .env file.

Good to know: Manual signal handling is not available in next dev .

Источник

Static Site Generation (SSG)

If a page uses Static Generation, the page HTML is generated at build time. That means in production, the page HTML is generated when you run next build . This HTML will then be reused on each request. It can be cached by a CDN.

In Next.js, you can statically generate pages with or without data. Let’s take a look at each case.

Static Generation without data

By default, Next.js pre-renders pages using Static Generation without fetching data. Here’s an example:

function About()  return div>Aboutdiv> > export default About

Note that this page does not need to fetch any external data to be pre-rendered. In cases like this, Next.js generates a single HTML file per page during build time.

Static Generation with data

Some pages require fetching external data for pre-rendering. There are two scenarios, and one or both might apply. In each case, you can use these functions that Next.js provides:

  1. Your page content depends on external data: Use getStaticProps .
  2. Your page paths depend on external data: Use getStaticPaths (usually in addition to getStaticProps ).

Scenario 1: Your page content depends on external data

Example: Your blog page might need to fetch the list of blog posts from a CMS (content management system).

// 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>  ) >

To fetch this data on pre-render, Next.js allows you to export an async function called getStaticProps from the same file. This function gets called at build time and lets you pass fetched data to the page’s props on pre-render.

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,  >,  > >

To learn more about how getStaticProps works, check out the Data Fetching documentation.

Scenario 2: Your page paths depend on external data

Next.js allows you to create pages with dynamic routes. For example, you can create a file called pages/posts/[id].js to show a single blog post based on id . This will allow you to show a blog post with id: 1 when you access posts/1 .

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.

So your page paths that are pre-rendered depend on external data**.** To handle this, Next.js lets you export an async function called getStaticPaths from a dynamic page ( pages/posts/[id].js in this case). This function gets called at build time and lets you specify which paths you want to pre-render.

// 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 > >

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:

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 >> >

To learn more about how getStaticPaths works, check out the Data Fetching documentation.

When should I use Static Generation?

We recommend using Static Generation (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.

You can use Static Generation for many types of pages, including:

  • Marketing pages
  • Blog posts and portfolios
  • E-commerce product listings
  • Help and documentation

You should ask yourself: «Can I pre-render this page ahead of a user’s request?» If the answer is yes, then you should choose Static Generation.

On the other hand, Static Generation is not a good idea if you cannot pre-render a page ahead of a user’s request. Maybe your page shows frequently updated data, and the page content changes on every request.

In cases like this, you can do one of the following:

  • Use Static Generation with Client-side data fetching: You can skip pre-rendering some parts of a page and then use client-side JavaScript to populate them. To learn more about this approach, check out the Data Fetching documentation.
  • Use Server-Side Rendering: Next.js pre-renders a page on each request. It will be slower because the page cannot be cached by a CDN, but the pre-rendered page will always be up-to-date. We’ll talk about this approach below.

Источник

Оцените статью