Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on May 10, 2021. It is now read-only.

Build and deploy Next.js applications with Server-Side Rendering on Netlify!

License

NotificationsYou must be signed in to change notification settings

netlify/next-on-netlify

Repository files navigation

We are deprecatingnext-on-netlify in favor of Netlify'sEssential Next.js Build Plugin. Please visitthis issue to learn more about the deprecation ofnext-on-netlify and ask any questions. You can also visit our simpleMigration doc for assistance migrating to the plugin.

Next.js on Netlify

next-on-netlify is a utility for enabling server-side rendering in Next.js on Netlify. It wraps your application in a tiny compatibility layer, so that pages can use Netlify Functions to be server-side rendered.

Table of Contents

Installation

npm install --save next-on-netlify

Setup

1. Set Next.js target to serverless

We must build our Next.js app as a serverless app. You can read more about serverless Next.jshere.

It's super simple. Just create anext.config.js file in the root of your project and write the following:

// next.config.jsmodule.exports={// Target must be serverlesstarget:"serverless",};

If binaries are needed in the deployment the following configuration is needed (Prisma is an example):

// next.config.jsmodule.exports={// Target must be experimental-serverless-trace// Your build time will be longer with this optiontarget:"experimental-serverless-trace",};

2. Add postbuild hook

The next-on-netlify package adds thenext-on-netlify command. When we run this command, some magic happens to prepare our Next.js app for hosting on Netlify*.

We want the next-on-netlify command to run after we build our Next.js application. So let's add a postbuild hook to our package.json file. You should add"postbuild": "next-on-netlify" to the existing scripts, like so:

{  "name": "my-nextjs-app",  "scripts": {    "dev": "next",    "build": "next build",    "postbuild": "next-on-netlify"  },  ...}

*If you're curious about the "magic", check out the well-documentednext-on-netlify.js file.

3. Configure for Netlify

We're almost done! We just have to tell Netlify how to build our Next.js app, where the functions folder is located, and which folder to upload to its CDN. We do that with anetlify.toml file in the root of your project and the following instructions:

[build]command   ="npm run build"functions ="out_functions"publish   ="out_publish"

Note:out_functions andout_publish are hard-coded into next-on-netlify.These are not configurable at the moment.

(Optional) Configure private git submodules

If your project contains private submodules, in order to deploy it, you willneed to:

  1. Generate a DeployKeyin Netlify andadd it to the relevantsubmodulesso that they can be cloned during the deploy process.

  2. Ensure the submodule remotes are set to SSH format (i.e.git@github.com:owner/project.git, nothttps://...). Inside the submoduledirectory, the git remote can be updated with:

    # git remote set-url [remote] [url]git remote set-url origin git@github.com:owner/project.git

We're done. Let's deploy 🚀🚀🚀

If you're not familiar with Netlify, follow the deployment instructions here:https://www.netlify.com/blog/2020/11/30/how-to-deploy-next.js-sites-to-netlify/

Demo

Optional Extras

Preview Locally

I recommend you still usenext dev to build and preview your application locally.

But if you want to emulate the Netlify deployment on your computer, you can also runnext-on-netlify locally and then usenetlify-cli to preview the result.

First, install the latest version ofnetlify-cli (you can alsolook at package.json to see the version that next-on-netlify has been tested against):

npm install -g netlify-cli

Then, add the following[dev] block to yournetlify.toml:

# netlify.toml# [build]#   ...[dev]functions ="out_functions"publish   ="out_publish"# We manually set the framework to static, otherwise Netlify automatically# detects Next.js and redirects do not work.# Read more: https://github.com/netlify/cli/blob/master/docs/netlify-dev.md#project-detectionframework ="#static"

Lastly, add the following lines to your.gitignore:

# .gitignore# Files generated by next-on-netlify command/out_publish//out_functions/

Now you're all set.

From now on, whenever you want to preview your application locally, just run:

  1. npx next-on-netlify watch: This will runnext build to build your Next.js app andnext-on-netlify to prepare your Next.js app for compatibility with Netlify. Any source code changes will trigger another build.
  2. netlify dev: This will emulate Netlify on your computer and let you preview your app onhttp://localhost:8888.

Note:

Preview Mode is not yet available locally, runningnetlify dev, for static pages without revalidate or fallback. This will be supported soon.

For now, Preview Modeis supported in production for all Next.js page types.

Custom Netlify Redirects

You can define custom redirects in a_redirects and/or in yournetlify.toml file.The precedence of these rules are:

  • _redirects
  • next-on-netlify redirects

Currently, there is no support for redirects set in yournetlify.toml file.

Read more about Netlify redirects here.

Custom Netlify Functions

next-on-netlify creates one Netlify Function for each of yourSSR pages and API endpoints. Currently, you can only create custom Netlify functions using@netlify/plugin-nextjs.

Background Functions

If your Next.js API page/route ends in-background, it will be treated as aNetlify background function.Note: background functions are only available on certain plans.

Using Netlify Identity

You can useNetlify Identity withnext-on-netlify. For all pages with server-side rendering (getInitialProps*, getServerSideProps, and API routes), you can access theclientContext object via thereq parameter.

For example:

constPage=()=><p>Hello World!</p>;exportconstgetServerSideProps=async({ req})=>{// Get event and context from Netlify Functionconst{netlifyFunctionParams:{ event, context},}=req;// Access Netlify identityconst{ identity, user}=context.clientContext;return{props:{},};};exportdefaultPage;

To access Netlify Identity from pages without server-side rendering, you can create aNext API route that performs identity-related logic:

exportdefaultasyncfunctiongetUser(req,res){// Get event and context from Netlify Functionconst{netlifyFunctionParams:{ event, context},}=req;// Access Netlify identityconst{ user}=context.clientContext;// Respond with user objectres.json({ user});}

* Note that pages using getInitialProps are only server-side rendered on initial page load and not when the user navigates client-side between pages.

Caveats

Fallbacks for Pages withgetStaticPaths

Fallback pages behave differently withnext-on-netlify than they do with Next.js. On Next.js, when navigating to a path that is not defined ingetStaticPaths, it first displays the fallback page. Next.js then generates the HTML in the background and caches it for future requests.

Withnext-on-netlify, when navigating to a path that is not defined ingetStaticPaths, it server-side renders the page and sends it directly to the user. The user never sees the fallback page. The page is not cached for future requests.

For more on this, see:Issue #7

next/image

Our existing solution for next/image is not very performant. We have performance improvements on our roadmap, dependent on internal work.

To get better performance now, we recommend using a cloud provider like Cloudinary (see the Next.js docs).

Credits

This package is maintained byLindsay Levine,Finn Woelm, andCassidy Williams.

📣 Shoutout to@mottox2 (a pioneer of hosting Next.js on Netlify) and@danielcondemarin (author of serverless-next.js for AWS). The two were big inspirations for this package.

🙌 Big "thank you" to the following people for their contributions, support, and beta testing:

Showcase

The following sites are built withnext-on-netlify:

opinionatedreact.com
opinionatedreact.com (via Twitter)

missionbit.org
missionbit.org (#18)

gemini.com

gemini.com

bigbinary.com

bigbinary.com

next-cms-ghost

Create your own blog and deploy to Netlify!

Are you building something awesome withnext-on-netlify? 🔥 Let us know and we will feature it here :)

About

Build and deploy Next.js applications with Server-Side Rendering on Netlify!

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Contributors29


[8]ページ先頭

©2009-2025 Movatter.jp