Version 4 of the Next Runtime adds support for native Next.js
rewrites and
redirects. These are defined in your next.config.js
file and include support for some features that are not included in Netlify redirects and rewrites.
Every site on Netlify supports redirects and rewrites, which are defined
in a _redirects
file or netlify.toml
, and sites that use the Next Runtime are no exceptions. However there are some
caveats to bear in mind when using them. The Next Runtime generates several rewrites of its own, which are used to map
paths from the site to different Netlify Functions which handle SSR, preview mode and images, as well as assets in
/_next/static
. Any Netlify redirects or rewrites that you create
take precedence over these rewrites, so you should avoid adding a root-level Netlify
rewrite, because that would override the rewrites generated by and required by the runtime.
Rewrites and redirects are applied in the following order:
- Redirects and rewrites in the
_redirects
file. These are read in order until a match is found, and then processing stops. - Redirects and rewrites in the
netlify.toml
file. None of these are read if one previous rules has already matched. - At this point, if the request targets a static file then it will be returned, without the Next.js redirects or rewrites being evaluated.
- Any request that does not target a static file will then be passed to Next.js, and then will evaluate redirects and
rewrites (which are defined in the
next.config.js
file).
Netlify and Next.js redirects support different features and are evaluated at different points in the request lifecycle, so there are some considerations in deciding which one to use with your site.
- Generally if your redirect can be handled with Netlify redirects, these are faster to evaluate and should be preferred.
- Identity, proxying and country-based redirects are Netlify-specific features and must use Netlify redirects.
- If you need redirects or rewrites to be applied before loading static files, you must use Netlify redirects and rewrites.
- If you are using a rewrite that points to a dynamic Next.js page, you must use Next.js rewrites. Next.js has no way of knowing what the rewritten page is when using Netlify rewrites, so the wrong page is likely to be rendered. This only applies to rewrites, not redirects.
- If you need Next.js-specific features such as regex path or header matching, you must use Next.js rewrites.
If you are using _redirects
or _headers
files rather than a netlify.toml
file, bear in mind that these files must
be in the published directory of your site, not the root of the repo. To do this, put them in public
and they will be
moved into .next
at build time. Do not put them directly into .next
, because it is emptied at build time. Any
_redirects
or _headers
files in the root of the repo will not be found when deployed.