Setting up Next.js URL Rewrites with Netlify

Setup Next.js URL Rewrites with Netlify

A Guide in Setting up URL Rewrites for Next.js applications Hosted in Netlify

As developers, we use URL rewrites for different reasons in an application. For example, sometimes, we rewrite URLs into short form to facilitate memorizing them. On the other hand, we can use keywords in the URL to make them SEO friendly.

Besides, with Next.js, URL paths are dependent on the project folder structure. For instance, if we put an About page inside a folder named Company, it will get reflected in the URL by default as /company/about. However, we could make it less dependent on the project folder structure by using URL rewrites.

In this article, I will discuss how to set up URL rewrites in Next.js with Netlify.

URL rewrite in Next.js

Let us see how to set up a simple URL rewrite with Next.js. For that, I have created a simple Next.js project and a new page called “about”.

About page code

Usually, when we run this application, we can visit the About page by typing localhost:3000/about in the browser’s address bar. However, we will define a simpler URL for the About page with a URL rewrite. Developers can use rewrites to map an incoming request path to a different destination path.

In Next.js, we can define URL rewrites in the next.config.js file. For example, the following code snippet shows how to write a simple rewrite in the next.config.js file.

const nextConfig = {
reactStrictMode: true,
async rewrites() {
return [
{
source: '/info',
destination: '/about'
}
]
}
}

module.exports = nextConfig

Here we have used the async function rewrites() that returns an array of objects. The object contains the source and destination properties. The source is the incoming request path pattern. The destination is the path you want to route to. For example, users can go to the about page with this configuration by typing <BASE_URL>/info in the address bar.

Also, there are some other properties in the objects mentioned above. To learn more about URL rewrites in Next.js, refer to the Next.js official documentation.

So, let’s look at how we can set up URL rewrites of our Next.js project with Netlify.

URL rewrite with Netlify

There are two main ways to configure URL rewrites with Netlify for a Next.js project. One way is to use the above discussed native Next.js rewrites configuration with Netlify plugins, and the other way is to use Netlify redirects and rewrites configurations directly.

Using Netlify Plugins to interpret Next.js Rewrite Rules

Deploying a Next.js site on Netlify automatically gets all the necessary dependencies, including the Essential Next.js plugin. This plugin configures your Netlify site to allow essential Next.js capabilities.

Version 4 of the Essential Next.js plugin supports native Next.js rewrites and redirects. In addition, it provides three serverless methods for dealing with SSR pages, ISR, and images.

The Essential Next.js plugin supports native Next.js rewrites and redirects. As explained previously in the article, these are configured in the next.config.js file. So, when you deploy a Next.js application on Netlify, install the Essential Next.js plugin to your site.

Netlify plugins tab

Using Netlify Native Redirect & Rewrite Configurations

There are two ways to configure redirect and rewrite rules for Netlify sites.

Save a plain text file named _redirects without a file extension to your site’s publish directory (within the /public directory). Each line has the original path and a new path. You may change the redirect behavior by appending parameters to the end of each line, such as HTTP status code, country conditions, or language conditions.

/info    /about    200

In the above example, we have redirected the /info to /about path, adding the status code 200. It becomes a rewrite when you provide the HTTP status code 200 to a redirect rule.

Also, we can configure redirects and rewrites in the Netlify configuration file. We can add one or more redirect rules. The following example shows how to define redirects in the netlify.toml file.

[[redirects]]
from = "/info"
to = "/about"
status = 200
force = true

As mentioned before, when you provide a redirect rule and an HTTP status code of 200, it becomes a rewrite. This implies that the URL in the user’s address bar remains unchanged, but Netlify’s servers fetch the new destination in the background. So in this example, users can go to /about page by going to /info path.

Find more about rewrites and redirects in the Netlify documentation.

More about Rewrite and Redirect Configurations

Rewrites and redirects we discussed above are applied in the following order,

  1. _redirects file has the top priority.
  2. Then the netlify.toml file. None of these are read if the previous rule is already matched.
  3. If the request is for a static file, it will be returned at this point without the Next.js redirects or rewrites being assessed.
  4. Any request that isn’t directed to a static file will be forwarded to Next.js, which will assess the redirects and rewrites configured in the next.config.js file.

Because Netlify and Next.js redirects have distinct features and are evaluated at various times in the request lifecycle, there are certain things to consider when picking which to employ with your site. Also, using multiple rewriting or redirecting options may cause conflicts during the build time. When we use _redirect file and next.config.js file together for redirects or rewrites, there could be conflicts. So, be aware of that.

When to use Next.js Rewrites or Redirects

  • You must utilize Next.js rewrites if you’re utilizing a rewrite that leads to a dynamic Next.js page. When utilizing Netlify rewrites, Next.js does not know what the rewritten page is. Hence the erroneous page is likely to be served. This only applies to rewrites; redirects are not affected.
  • You must utilize Next.js rewrites if you need Next.js-specific functionality like regex path or header matching.

When to use Netlify Rewrites or Redirects

  • If your redirect can be handled using Netlify redirects, these are often faster to analyze and should be chosen.
  • Netlify-only functionalities like identity, proxying, and country-based redirects need Netlify redirects.
  • You must utilize Netlify redirects and rewrites if you need to apply redirects or rewrites before loading static files.

However, the above options discussed have the limitation of using variables in rewrite rules. Therefore, let’s look at a custom approach to support it in practice.

Using Dynamic Rewrite Rules

Think of a scenario where you want to rewrite a path using one of the environment variables we defined. It can be useful to configure different rewrites in different stages of your project, such as “development” and “production”.

To overcome this limitation, we can define a Netlify environment variable with redirect/rewrite information and dynamically create the _redirects file using that environment variable.

As an example, if we create an environment variable NETLIFY_REDIRECT=”/info /about 200″ and define the build command as printf /”$NETLIFY_REDIRECT/” > public/_redirects && next build. This will solve the problem we discussed previously.

Environment variable in Netlify
Build command to create _redirect file dynamically

Conclusion

This article discussed different ways to configure rewrite rules of a Next.js application hosted in Netlify. Ether, you can use the netlify.config.js file to configure rewrites and use the Essential Next.js plugin, or you can use native Netlify rewrite options by writing rewrite rules in the redirects file or netlify.toml file. Also, we discussed a way to create _redirects file with Netlify environment variables dynamically.

That’s it for this article. I hope you have acquired a good understanding of URL rewriting and setting it up on Next.js and Netlify.

Bit: Feel the power of component-driven dev

Say hey to Bit. It’s the #1 tool for component-driven app development.

With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.

  • Create and compose “app building blocks”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
  • Easily share, and reuse components as a team.
  • Quickly update components across projects.
  • Make hard things simple: Monorepos, design systems & micro-frontends.

Try Bit open-source and free→

Learn more


Setting up Next.js URL Rewrites with Netlify was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Osusara Kammalawatta

Setup Next.js URL Rewrites with Netlify

A Guide in Setting up URL Rewrites for Next.js applications Hosted in Netlify

As developers, we use URL rewrites for different reasons in an application. For example, sometimes, we rewrite URLs into short form to facilitate memorizing them. On the other hand, we can use keywords in the URL to make them SEO friendly.

Besides, with Next.js, URL paths are dependent on the project folder structure. For instance, if we put an About page inside a folder named Company, it will get reflected in the URL by default as /company/about. However, we could make it less dependent on the project folder structure by using URL rewrites.

In this article, I will discuss how to set up URL rewrites in Next.js with Netlify.

URL rewrite in Next.js

Let us see how to set up a simple URL rewrite with Next.js. For that, I have created a simple Next.js project and a new page called “about”.

About page code

Usually, when we run this application, we can visit the About page by typing localhost:3000/about in the browser's address bar. However, we will define a simpler URL for the About page with a URL rewrite. Developers can use rewrites to map an incoming request path to a different destination path.

In Next.js, we can define URL rewrites in the next.config.js file. For example, the following code snippet shows how to write a simple rewrite in the next.config.js file.

const nextConfig = {
reactStrictMode: true,
async rewrites() {
return [
{
source: '/info',
destination: '/about'
}
]
}
}

module.exports = nextConfig

Here we have used the async function rewrites() that returns an array of objects. The object contains the source and destination properties. The source is the incoming request path pattern. The destination is the path you want to route to. For example, users can go to the about page with this configuration by typing <BASE_URL>/info in the address bar.

Also, there are some other properties in the objects mentioned above. To learn more about URL rewrites in Next.js, refer to the Next.js official documentation.

So, let’s look at how we can set up URL rewrites of our Next.js project with Netlify.

URL rewrite with Netlify

There are two main ways to configure URL rewrites with Netlify for a Next.js project. One way is to use the above discussed native Next.js rewrites configuration with Netlify plugins, and the other way is to use Netlify redirects and rewrites configurations directly.

Using Netlify Plugins to interpret Next.js Rewrite Rules

Deploying a Next.js site on Netlify automatically gets all the necessary dependencies, including the Essential Next.js plugin. This plugin configures your Netlify site to allow essential Next.js capabilities.

Version 4 of the Essential Next.js plugin supports native Next.js rewrites and redirects. In addition, it provides three serverless methods for dealing with SSR pages, ISR, and images.

The Essential Next.js plugin supports native Next.js rewrites and redirects. As explained previously in the article, these are configured in the next.config.js file. So, when you deploy a Next.js application on Netlify, install the Essential Next.js plugin to your site.

Netlify plugins tab

Using Netlify Native Redirect & Rewrite Configurations

There are two ways to configure redirect and rewrite rules for Netlify sites.

Save a plain text file named _redirects without a file extension to your site’s publish directory (within the /public directory). Each line has the original path and a new path. You may change the redirect behavior by appending parameters to the end of each line, such as HTTP status code, country conditions, or language conditions.

/info    /about    200

In the above example, we have redirected the /info to /about path, adding the status code 200. It becomes a rewrite when you provide the HTTP status code 200 to a redirect rule.

Also, we can configure redirects and rewrites in the Netlify configuration file. We can add one or more redirect rules. The following example shows how to define redirects in the netlify.toml file.

[[redirects]]
from = "/info"
to = "/about"
status = 200
force = true

As mentioned before, when you provide a redirect rule and an HTTP status code of 200, it becomes a rewrite. This implies that the URL in the user’s address bar remains unchanged, but Netlify’s servers fetch the new destination in the background. So in this example, users can go to /about page by going to /info path.

Find more about rewrites and redirects in the Netlify documentation.

More about Rewrite and Redirect Configurations

Rewrites and redirects we discussed above are applied in the following order,

  1. _redirects file has the top priority.
  2. Then the netlify.toml file. None of these are read if the previous rule is already matched.
  3. If the request is for a static file, it will be returned at this point without the Next.js redirects or rewrites being assessed.
  4. Any request that isn’t directed to a static file will be forwarded to Next.js, which will assess the redirects and rewrites configured in the next.config.js file.

Because Netlify and Next.js redirects have distinct features and are evaluated at various times in the request lifecycle, there are certain things to consider when picking which to employ with your site. Also, using multiple rewriting or redirecting options may cause conflicts during the build time. When we use _redirect file and next.config.js file together for redirects or rewrites, there could be conflicts. So, be aware of that.

When to use Next.js Rewrites or Redirects

  • You must utilize Next.js rewrites if you’re utilizing a rewrite that leads to a dynamic Next.js page. When utilizing Netlify rewrites, Next.js does not know what the rewritten page is. Hence the erroneous page is likely to be served. This only applies to rewrites; redirects are not affected.
  • You must utilize Next.js rewrites if you need Next.js-specific functionality like regex path or header matching.

When to use Netlify Rewrites or Redirects

  • If your redirect can be handled using Netlify redirects, these are often faster to analyze and should be chosen.
  • Netlify-only functionalities like identity, proxying, and country-based redirects need Netlify redirects.
  • You must utilize Netlify redirects and rewrites if you need to apply redirects or rewrites before loading static files.

However, the above options discussed have the limitation of using variables in rewrite rules. Therefore, let’s look at a custom approach to support it in practice.

Using Dynamic Rewrite Rules

Think of a scenario where you want to rewrite a path using one of the environment variables we defined. It can be useful to configure different rewrites in different stages of your project, such as “development” and “production”.

To overcome this limitation, we can define a Netlify environment variable with redirect/rewrite information and dynamically create the _redirects file using that environment variable.

As an example, if we create an environment variable NETLIFY_REDIRECT="/info /about 200" and define the build command as printf /"$NETLIFY_REDIRECT/" > public/_redirects && next build. This will solve the problem we discussed previously.

Environment variable in Netlify
Build command to create _redirect file dynamically

Conclusion

This article discussed different ways to configure rewrite rules of a Next.js application hosted in Netlify. Ether, you can use the netlify.config.js file to configure rewrites and use the Essential Next.js plugin, or you can use native Netlify rewrite options by writing rewrite rules in the redirects file or netlify.toml file. Also, we discussed a way to create _redirects file with Netlify environment variables dynamically.

That’s it for this article. I hope you have acquired a good understanding of URL rewriting and setting it up on Next.js and Netlify.

Bit: Feel the power of component-driven dev

Say hey to Bit. It’s the #1 tool for component-driven app development.

With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.

  • Create and compose “app building blocks”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
  • Easily share, and reuse components as a team.
  • Quickly update components across projects.
  • Make hard things simple: Monorepos, design systems & micro-frontends.

Try Bit open-source and free→

Learn more


Setting up Next.js URL Rewrites with Netlify was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Osusara Kammalawatta


Print Share Comment Cite Upload Translate Updates
APA

Osusara Kammalawatta | Sciencx (2022-07-14T07:03:04+00:00) Setting up Next.js URL Rewrites with Netlify. Retrieved from https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/

MLA
" » Setting up Next.js URL Rewrites with Netlify." Osusara Kammalawatta | Sciencx - Thursday July 14, 2022, https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/
HARVARD
Osusara Kammalawatta | Sciencx Thursday July 14, 2022 » Setting up Next.js URL Rewrites with Netlify., viewed ,<https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/>
VANCOUVER
Osusara Kammalawatta | Sciencx - » Setting up Next.js URL Rewrites with Netlify. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/
CHICAGO
" » Setting up Next.js URL Rewrites with Netlify." Osusara Kammalawatta | Sciencx - Accessed . https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/
IEEE
" » Setting up Next.js URL Rewrites with Netlify." Osusara Kammalawatta | Sciencx [Online]. Available: https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/. [Accessed: ]
rf:citation
» Setting up Next.js URL Rewrites with Netlify | Osusara Kammalawatta | Sciencx | https://www.scien.cx/2022/07/14/setting-up-next-js-url-rewrites-with-netlify/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.