Skip to content
Join live – Get insights, tips, + Q&A from Sanity developers on our latest releases
Sanity
    • Platform

      Sanity Studio

      Flexible editing environment

      APIs

      Connect to anything

      Content Lake

      Real-time database

      Try product demo

      Features

      Real-time collaboration

      Fearlessly work with content

      Precise content querying

      Treat content as data with GROQ

      Localization

      Coherent messaging across territories

    • Use cases

      E-commerce

      Richer shopping experiences

      Marketing sites

      Control your story

      Products & services

      Innovate and automate

      Mobile apps

      Content backend for every OS

      View all

      Integrations

      Shopify
      Mux
      Vercel
      Netlify
      Algolia
      Cloudinary
      BigCommerce
      Commerce Layer
      Smartling
      Transifex
      View all
    • Learn

      Documentation
      Studio API Reference
      API reference
      Guides
      GROQ cheat sheet
      Sanity UI
      Get started

      Build and share

      Templates
      Tools and plugins
      Schemas and snippets
      Project showcase
      Share your work
      Browse Exchange

      Frameworks

      React
      Vue
      Next.js
      Nuxt.js
      Svelte
      Remix
      Gatsby
      Astro
      Angular
      Eleventy
      View all
    • Discover

      Blog
      Resource library
      Glossary
      Agency partners
      Become a partner
      Technical support
      Talk to sales

      Case studies

      Puma

      Source of truth for global markets

      Aether

      Unique digital shopping experience

      Morning Brew

      Omnichannel media distribution

      InVision

      Delivering exceptional customer experiences

      View all

      Popular guides

      Headless CMS
      Structured content
      Content modeling
      Headless SEO
      Static websites
      View all
    • Enterprise
    • Pricing
    • Log in
    • Contact sales
    • Get started
Contact salesGet started
Published May 22nd 2018

Tutorial: Hosting your Next.js frontend on Netlify in 5 minutes

Do you want to host your Sanity backed Next.js frontend on Netlify? No problem! Just follow these few steps to get going.

Knut Melvær

Principal Developer Marketing Manager

If you followed the instruction of the first blog tutorial, you now already have a blog that can be hosted on any environment that runs node, be it Zeit’s now, Heroku or your own server (bless you!). But what if you wanted to host it on an awesome static site host like Netlify? Well, look no further, here is how to go about it.

Next.js comes with the ability to export as a static standalone app. Where Next.js works as a single page application with server-side rendering out of the box, such an export will build web pages as .html-files in folders, just like the old days. You will still get most of the features like prefetching and so on though.

If you just want go check out the code, you can find it on GitHub.

1. Add the export command to package.json

This feature is available under the command next export, which you will have to add to your scripts. I chose to make a new entry, called export, and chain it after the build step.

{
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js",
    "export": "npm run build && next export"
  }
}

2. Tell Next.js where to get the page content in next.config.js

If you try to run npm run export you will get some error messages, among them telling you that No "exportPathMap" found in "next.config.js". Next.js will then try to build the pages from what it sees in the pages-folder, but since our blog.js expects a query parameter (that's is a slug from the URL) it will also fail. Next.js doesn't know (yet) what posts we have published in Sanity. So we have to configure Next.js to go look for those, before trying to export them. We start by adding a file to the root-folder called next.config.js. In this file, we'll put a configuration script and export it as a JavaScript module.

// next.config.js
/*
 * Let's reuse the client configuration. I have rewritten
 * it as a CommonJS module just to make it runs in a Node
 * environment without any fuzz.
 */

const client = require('./client')

module.exports = {
  // Make sure that your node enviroment supports async/await
  exportPathMap: async function (defaultPathMap) {
  
    const path = await client
      // get all the posts and return those with slugs
      .fetch('*[_type == "post"].slug.current')
      .then(data =>
        // use reduce to build an object with routes
        // and select the blog.js file, and send in the
        // correct query paramater.
        data.reduce(
          (acc, slug) => ({
            '/': { page: '/' },
            ...acc,
            [`/blog/${slug}`]: { page: '/blog', query: { slug } }
          }),
          {}
        )
      )
      .catch(console.error)
    return path
  }
}

This script will make an API call to your Sanity project, and get a list of slugs back. Here I use the wonderful ES6-function .reduce() to loop through all the slugs, and build an object of paths that Next.js, in turn, can use to generate the static pages. The object this functions ends up with looks something like this:

const path = {
  "/": { 
    page: "/" 
  },
  "/blog/hello-world": { 
    page: "/blog",
    query: { 
      slug: "hello-world"
    } 
  }
}

This is a simple example constrained to just the blog posts, but as you might suspect, we could make far more sophisticated with standalone pages, different content types and nifty stuff using query parameters.

And that's pretty much it for the coding part. Test your script locally by running npm run export first. You should end up with a new folder called out, with an index.html file in it, in addition to two folders called _next and blog. Let’s put those on the web 🚀

3. Deploy your blog on Netlify

Push your code to a Github repository (or GitLab, or Bitbucket) and go to netlify.com. Sign in to a free account using your Github credentials (or some of the others if you prefer). Click on the New site from Git button. Click through the Git provider steps in order to find your blog repository and choose that. You'll now be presented with some few setup screens that looks like this:

Netlify deploy settings

Choose the branch you want to deploy from, and add npm run export as the build command and out as the publish directory. Click Deploy site when you've done this, and wait in anticipation while the build log scrolls in front of you. It can't be that easy? Yes, it can.

4. Add your blog URL to Sanity’s CORS settings

Hopefully, the deployment was successful and you're presented with a screen that tells you the project URL on Netlify and additional settings for your project. You can go ahead and choose your own site name on Netlify under Site settings, which will give you a new URL from the randomly generated one. Netlify also accepts your own custom domain if you prefer that. Either way, you have to take whatever domain you want to access your blog from, and add that to your Sanity project’s CORS-settings. Even if this is a static export, it seems that Next.js will do some client-side API-calls for prefetching and so on.

And that's it. You're good to go. Netlify has a couple of other nifty features to, such as webhooks, functions and even split testing. We get back to some of those in later tutorials, but do go explore!

Page content

  • 1. Add the export command to package.json
  • 2. Tell Next.js where to get the page content in next.config.js
  • 3. Deploy your blog on Netlify
  • 4. Add your blog URL to Sanity’s CORS settings

Product

Sanity StudioAPIsContent LakeSecurity & Compliance
  • Sanity vs Contentful
  • Sanity vs Strapi
  • Sanity vs Wordpress
  • Sanity vs Adobe Experience Manager
  • Sanity vs Hygraph
  • Sanity vs Sitecore
  • Sanity vs Storyblok
  • Sanity vs Contentstack
  • Sanity vs Prismic
  • Sanity vs Drupal
  • Sanity vs ButterCMS

Resources

DocumentationBlogResource libraryCase Studies
  • React Blog
  • Gatsby Blog
  • Next.js Landing Pages
  • Making a PWA
  • Single Page Application
  • Svelte & Typescript App
  • Vue & Tailwind Blog
  • Developer Portfolio Templates
  • Form validation with Yup
  • Live Preview with Next.js and Sanity.io
  • Next.js blog
  • Next.js personal website
  • Clean Next.js + Sanity app
  • Clean Remix + Sanity app
  • Clean SvelteKit + Sanity app
  • All Templates
  • Agency partners
  • Technology partners
  • Headless CMS 101
  • Static Sites 101
  • Headless Commerce 101
  • CMS for enterprise
  • Headless SEO
  • Localization
  • Content as a Service
  • What is a DXP?
  • Typescript 101
  • Ecommerce SEO
  • What is a Composable DXP?
  • What is an API?
  • GraphQL vs REST
  • React CMS
  • Next.JS CMS
  • CMS for Shopify
  • API-first CMS
  • Content platform
  • Multilingual CMS
  • Static Site CMS
  • Gatsby CMS
  • Node CMS
  • E-commerce CMS
  • Vue CMS
  • Angular CMS
  • GraphQL CMS
  • Newspaper CMS
  • Magazine CMS
  • CMS for apps
  • Remix CMS
  • Nuxt CMS
  • SvelteKit CMS
  • Agile CMS
  • Eleventy CMS
  • Multisite CMS

Company

Contact SalesEnterpriseCareersTerms of ServicePrivacy PolicyAccessibility Statement

Stay connected

  • GitHub
  • Slack
  • Twitter
  • YouTube
  • Stack Overflow
  • Blog RSS
  • Newsletter
©Sanity 2023