From development to production with Sanity, Next JS, and Netlify
Tags: webdev, nextjs, netlify, github
Published: 2021-10-06 20:27:48

So far I've implemented two projects using the self-hosted Sanity Studio for content management, Next JS hosted in Netlify for the frontend portion and I can say I've learned a few things on how to make them work.

## Starting Point and Netlify

I'm going to assume that you have used them all, Sanity, Next, and Netlify. So you probably already know that Netlify deploys Next without issue by building and exporting everything before deployment.

The easiest way to use Netlify with your application is to use Continuous Deployment, which will connect to your favorite Git provider so when you push to it, your page will deploy and update automatically. You can also add a file called netlify.toml, that you can add to the root of your folder to indicate Netlify during deployment the commands you need to run your Next.js application.

```
[build]
command = "npm run build && npm run export"
publish = "out"

[[plugins]]
package = "netlify-plugin-cache-nextjs"

```

The problem with that is that in order to see a change in the project you would need to actually make a push so that Netlify redeploys the whole site every time and that's not what we want, we want the page to receive updates and create new content without deploying the whole site.

For that, we can start by changing our netlify.toml file to only build the app but not export it. The Next export command is not intended for scenarios like the one we want, where we could update data after deployment so we have to remove it.

```
[build]
command = "npm run build"

[[plugins]]
package = "netlify-plugin-cache-nextjs"

```
## Data Fetching, and Incremental Static Regeneration

If you have used Next.js before, you will be familiar with the two Next's unique functions to fetch data while generating your site statically:

* getStaticProps
* getStaticPaths

Both of these functions work perfectly when fetching data at build time, as in our case with Netlify while deployment the props and paths help you generate the pages so that everything seems faster on the client-side.

The real problem is that in our case we have a content manager, so our goal is to update the website after it was deployed. If we didn't change anything in our files and kept the props, paths, and Netlify configuration as it was, this wouldn't be possible without pushing again via Git and rebuild the entire website from scratch.

To solve this, Next.js has something called Incremental Static Regeneration, which allows you to create or update the static pages after you've built the site. You can enable ISR on a per-page basis, making everything even more efficient by retaining the benefits of static generation while adding new content.

### getStaticProps

Let's see the code below for a better understanding. You have your basic getStaticProps function that will run a function called getAllBlogs and await the response from the Sanity Client, after returning the information will go to props as usual, but now we have an extra line called revalidate. This property will enable ISR and indicate Next.js that it needs to attempt to re-generate the page every n amount of seconds, in our case, every 5 seconds.


```jsx
export async function getStaticProps() {
  const allBlogPosts = await getAllBlogs();
  return {
    props: {
      allBlogPosts,
    },
    revalidate: 5,
  };
}
```

The trick is, that if the page was pre-rendered at build time, like in our case, Next.js will initially show the cached page. After the 5-second window, all new requests will trigger the regeneration in the background and wait until it's finished to invalidate the cache and show the updated page. In case the new regeneration fails, Next is smart enough to show the old page instead of showing an error.

### getStaticPaths

But what about creating new paths? For that, we can update the fallback key from false to blocking. Initially false indicated that any paths that were not returned by the function will result in a 404 page but with blocking, the new paths not returned by the function will wait for the HTML to be generated and then cached it in any future requests.

Now our getStaticPaths functions look like this:

```jsx
export async function getStaticPaths() {
  const allId = await sanityClient.fetch(
    `*[_type == "post"]{
            title,
            slug,
        }`
  );
  const paths = allId.map((id) => {
    return {
      params: {
        slug: id.slug.current.toString(),
      },
    };
  });
  return {
    paths,
    // This will server-render pages on-demand 
    // If the path doesn't exists
    fallback: 'blocking',
  };
}
```

## Conclusions

The combo of Next.js, Sanity, and Netlify is extremely powerful for freelance creators like me. Their free tier is a great hook for new and upcoming clients, as they normally don't want to invest a lot of money in server space that they won't need or use. So I truly appreciate how easy and simple the interaction between these technologies is.

If you want to see what I showed here implemented, you can visit the repo of my personal website [here](https://github.com/jesusrmz19/jesusrmz).

{% github jesusrmz19/jesusrmz%}