The latest features in Next.js
Tags: nextjs
Published: 2020-07-23 17:14:04

---
title: The latest features in Next.js
published: true
date: 2020-07-16 17:30:27 UTC
tags: nextjs
canonical_url: https://blog.logrocket.com/the-latest-features-in-next-js/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/xw1yszzikn18znlv719i.png
---
**Written by [Kapeel Kokane](https://blog.logrocket.com/author/kapeelkokane/)**✏️

## Introduction

In the context of SSR (server-side rendering) and static site generation in the recent past, [Next.js](http://www.nextjs.org) has built up a reputation that we cannot deny. In a short duration of a few years, it has become a [go-to framework](https://scotch.io/tutorials/top-10-static-site-generators-in-2020) when it comes to hosting static sites like landing pages, documentation, and blogs. In this article, let’s look at the major enhancements that got added to the framework as a part of their latest major release versions, [Next.js 9.3](https://nextjs.org/blog/next-9-3) and [Next.js 9.4](https://nextjs.org/blog/next-9-4).

## Optimized static site generation

Next.js is a hybrid framework, which lets us choose between static generation (SG) or server-side rendering (SSR). With Next.js 9.0, we saw the introduction of automatic static optimization which depended on the data-fetching method `getInitialProps()` to decide whether a page must be rendered as HTML at build time. But that has now been pushed to the next (pun intended) level by adding two new data-fetching methods `getStaticProps` & `getServerSideProps`. There’s also a `getStaticPaths` introduced to generate static pages for dynamic routes. Here’s how that works.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

### [getStaticProps](https://nextjs.org/blog/next-9-3#getstaticprops)

This is predominantly meant to enable static generation for your sites and configure the async data fetch to happen at build time (in the server context). Just export an `async` function called `getStaticProps` from your page and return an object with a `props` key from inside of it, which will get passed to the page as props:

```jsx
export async function getStaticProps(context) {
 return {
   props: {} // will be passed to the page component as props
 }
}
```

Next.js will then pre-render that page at build time by calling this function in the Node.js context. The benefit here is that we can fetch data using any method (even directly accessing a database) as this code will never run on the client-side.  
 ![staticProps](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/07/staticProps.png?resize=1262%2C757&ssl=1)

### [getStaticPaths](https://nextjs.org/blog/next-9-3#getstaticpaths)

This is used in conjunction with `getStaticProps` when dynamic paths are used in order to define a list of paths that are to be static rendered at build time.

Export an `async` function called `getStaticPaths` from your page that contains dynamic routes and Next.js will statically pre-render all paths specified by it:

```jsx
export async function getStaticPaths() {
 return {
   paths: [
     { params: { ... } }
   ],
   fallback: true // or false
 };
}
```

If the page uses dynamic routes named `pages/posts/[id].js`, exporting `[{params:{id:1}},{params:{id:2}}]` as the paths array will result in statically generating `post/1` and `posts/2` at build time.  
 ![static paths](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/07/staticPaths.png?resize=1262%2C757&ssl=1)  
Also, notice the fallback key being passed. If the value of `fallback` is false, then any path not returned in the `getStaticPaths` array will result in a **404 page** error.

### [getServerSideProps](https://nextjs.org/blog/next-9-3#getserversideprops)

This is used in a page to render the page on every fetch (SSR). While navigating using `next/link`, a request is made to the server, `getServerSideProps` is executed and results are returned back to the frontend. The returned result is passed to the page as props:

```jsx
export async function getServerSideProps(context) {
 return {
   props: {} // passed as props to page
 }
}
```

![server side props](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/07/serversideprops.png?resize=1262%2C757&ssl=1)

## Preview mode

A direct result of introducing `getStaticProps` and `getServerSideProps` is that conditional, on-demand rendering becomes possible with it.

A use case for preview mode is when you are working with a draft version of your CMS and want to preview the server-side rendered version of that instead of the statically generated output.

## ![previewMode](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/07/previewMode.png?resize=1262%2C757&ssl=1)Sass support and component-level styles

### [Sass support](https://nextjs.org/blog/next-9-3#built-in-sass-support-for-global-stylesheets)

Before the Next.js 9.3 release, developers used `next-sass` in order to use SASS stylesheets, but now, Next.js supports SASS out of the box. In order to use it, do `npm install sass`, then, create a standard .scss file and then import it into the `pages/_app.js`.

### [Component-level styles](https://nextjs.org/blog/next-9-3#built-in-sass-support-for-global-stylesheets)

From Next.js 9.3 onwards, it is now possible to define styles in the form of Global SASS as well as CSS Modules. The global styles can be used as above whereas component level styles can be defined by naming them as `[name].module.scss`. Modules avoid class name conflict by automatically generating unique class names.

![scss](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/07/scss.png?resize=1262%2C865&ssl=1)

### Enhanced 404 page

If a custom `pages/error.js` is not defined, Next.js will automatically, statically generate a 404 page and serve it whenever required. If the user needs to customize the error page, it can be done by creating a custom `pages/404.js` that will, again, statically be optimized at build time.

### Fast refresh

Developer experience forms a big chunk of the reason for the success/failure of any framework. With Next.js 9.4, a big improvement was made in the developer experience for Next.js developers via the fast-refresh, hot reloading experience, which is now enabled by default.

What this means is that Next.js will now only update the code file that got edited and rerender just that component, without losing component state. Other updates that also enhance the developer experience include:

- Error locations that point to the accurate row and column generating the error
- Click-to-open reference code snippets
- Automatic address of runtime errors after fixing those

### Enhanced `env` variables support

In the earlier versions of Next.js, it was pretty confusing for the developer to know if a particular environment variable is available only in the Node.js environment or also included in the browser bundle but that is solved with Next.js 9.4. Now, appending an environment variable with NEXT_PUBLIC_ makes sure that it will be inlined into the browser JavaScript bundle. Also, Next.js supports [.env loading](https://nextjs.org/docs/basic-features/environment-variables) by default.

### Enhanced fetch support

The fetch API which is used to make REST requests was polyfilled in the browser environment in the earlier releases. Now, in Next.js 9.4, `fetch()` is also polyfilled in the Node.js environment. That means, for the code that executes on the server side, the developer no longer needs to include third party libraries like `node-fetch` or `isomorphic-fetch`.

### Absolute imports

This is another one of those enhancements which were created to make the life of the developer a little less difficult. When nested deep into a component, in order to use any other piece of reusable code appearing higher up in the tree, the developer often ends up using this kind of syntax:

```jsx
import Icon from '../../../../shared/icon'
```

If the shared folder existed right in the root of the application, the developer should be able to access it like this:

```jsx
import Icon from 'shared/icon'
```

Which is now possible with Next.js using the `baseUrl` property in `jsconfig.json`/`tsconfig.json`. Also in the same context, it is now possible to create custom module aliases using the same config file as well. Here is how it looks:

```jsx
// tsconfig.json or jsconfig.json
{
 "compilerOptions": {
   "baseUrl": ".",
   "paths": {
     "@/design-system/*": ["components/design-system/*"]
   }
 }
}
```

After which, the component can be imported using this syntax:

```jsx
import Icon from '@/design-system/icon'
```

## Conclusion

In conclusion, the latest releases of Next.JS 9.3 and Next.js 9.4 have brought in significant improvements in all aspects. Right from core performance like static generation, server-side rendering, conditional preview mode to the surface level improvements. In terms of SASS support and developer experience improvements like fast refresh, env variable support, and absolute imports makes these new releases worthy of an upgrade. So if you are running an earlier version, do consider an update.

* * * 
## [LogRocket:](logrocket.com/devto) Full visibility into production React apps 

Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, [try LogRocket.](https://www2.logrocket.com/react-performance-monitoring)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/eq752g8qhbffxt3hp9t4.png)

[LogRocket](https://logrocket.com/devto) is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — [start monitoring for free.](https://www2.logrocket.com/react-performance-monitoring)
* * *

The post [The latest features in Next.js](https://blog.logrocket.com/the-latest-features-in-next-js/) appeared first on [LogRocket Blog](https://blog.logrocket.com).