Replies: 185 comments 41 replies
This comment has been hidden.
This comment has been hidden.
-
Would rewrites allow overwriting how next.js handles |
Beta Was this translation helpful? Give feedback.
-
Yep you'd be able to route Eg: { source: '/api/:rest*', destination: '/api-docs/:rest*' } |
Beta Was this translation helpful? Give feedback.
-
Hey Tim, I am just thinking out loud here, but one thing that may be really powerful about this approach would be the ability to have the A/B Testing Example: NOTE this is more or less just brainstorming something potentially useful 🤷♂ haha Absolutely love this direction you and team are headed! |
Beta Was this translation helpful? Give feedback.
-
@stormy251 This won't work as the output has to be static at build time. Eg for the serverless target. |
Beta Was this translation helpful? Give feedback.
-
I see, I had assumed that there was a reason for static remapping here. 👍 Thanks for the great work! I hope to free up some time to contribute to this project soon! |
Beta Was this translation helpful? Give feedback.
-
Great work 👌🏼 {
source: "/photos/*",
headers: {
"cache-control": "s-maxage=604800"
}
} |
Beta Was this translation helpful? Give feedback.
-
@danielcondemarin I brought that up when @Timer and me were discussing the spec (before it was posted) but don't think it's necessary for the initial implementation, it can be a separate RFC after this is shipped 👍 |
Beta Was this translation helpful? Give feedback.
-
This scenario is the last reason I use a custom server for one of my apps. It's a fairly complex application and we've just converted it to Next 9 and ripped out all of the custom server and the only bit that remains is a custom router to do this:
etc., since for SEO on this particular site these matter. With this RFC I could eliminate the custom server completely and that would be amazing, it is a huge headache to maintain the build stack for it. |
Beta Was this translation helpful? Give feedback.
-
Very useful proposal and something our team could use as well. I suggest breaking this proposal into two separate RFC's; one for Redirects and one for Rewrites. This might allow for easier collaborating and keep the discussion focused. |
Beta Was this translation helpful? Give feedback.
-
Happy to see this RFC. We use a custom server to point different routes to the same page, redirects in next.config could take care of it now. |
Beta Was this translation helpful? Give feedback.
-
Far out of the scope of this RFC, but I'd like this idea to be out there. Some day I'd love to be able to implement something like the following: // next.config.js
const path = require('path')
module.exports = {
async rewrites() {
return [
{
source: "/en/:path*",
destination: "/:path",
buildEnv: { LOCALE: 'en' }
},
{
source: "/fr/:path*",
destination: "/:path",
buildEnv: { LOCALE: 'fr' }
}
];
},
webpack (config, options) {
config.resolve.alias['messages'] =
path.join(__dirname, 'messages', options.buildEnv.LOCALE || 'en');
config.plugins.unshift(new webpack.DefinePlugin({
'process.env.CURRENT_LOCALE': options.buildEnv.LOCALE || 'en'
}));
return config
}
}; // /pages/welcome.jsx
import WelcomeMsg from 'messages/welcome'
export function () {
return (
<div>
Localized welcome message: <WelcomeMsg />
</div>
)
} The idea behind it would be to have pregenerated components for localized strings from a separate build step. Then next would build a bundle for each specific locale. Some of the advantages would be:
EDIT: Actually, I think |
Beta Was this translation helpful? Give feedback.
-
I was just about to start setting up a custom server to handle routing for our new e-commerce client serving 40k merchants with millions of products and a gazillion different URL's, so this RFC is perfectly timed! |
Beta Was this translation helpful? Give feedback.
-
So redirects I get, but aren't rewrites already covered in the dynamic |
Beta Was this translation helpful? Give feedback.
-
@pkrawc most rewrites cases are already handled by dynamic routes ( This feature would be for more advanced rewrites that validate parameters, etc.
|
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
I have this rewrite: When I'm on The following cause reloads: This does not, but of course that's not the URL I want: Am I doing something wrong? Or is this expected behavior? When loading |
Beta Was this translation helpful? Give feedback.
-
Has anyone successfully used the custom routes (rewrites) on vercel? See: #13347 |
Beta Was this translation helpful? Give feedback.
-
Hi @joafeldmann, the new custom routes in |
Beta Was this translation helpful? Give feedback.
-
Hi guys. What is the status of this proposal and can we have some documentation on redirects/rewrites? |
Beta Was this translation helpful? Give feedback.
-
Hello. How can we use custom routes accordingly with next/link without triggering a reload? In our case, we're trying to move our news websites to next.js. They have category and article pages. Categories are reachable under /category/subcategory and articles under /category/subcategory/article. There can be an infinite number of subcategories that can be created by our editors, so we don't know the structure of the nesting in advance. This works fine with our current setup. We're trying to replicate this with next.js without having to resort to a custom server. I set up rewrites in next.config.js that look like this:
This works fine when I enter the url directly, so I can open an article with /category/subcategory/slug. But if I try using this with nex/link it doesn't work properly. If I set href to
If I just use How can I achieve the desired behavior with custom routes and next/link? Is it even possible? Thanks! |
Beta Was this translation helpful? Give feedback.
-
Hi all, just wanted to mention that we have successfully leveraged rewrites in You can find the source code here. |
Beta Was this translation helpful? Give feedback.
-
Hi all! I think this issue has been fixed with Next JS 9.5? With this new feature: Support for Rewrites, Redirects, and Headers |
Beta Was this translation helpful? Give feedback.
-
Support for Custom Routes Support (Rewrites, Redirects, and Headers) has been released in Next.js 9.5 🥳 Check out the official docs to learn more about the usage: Before using Rewrites, Redirects or Headers, update to the latest version: npm install next@latest
# or with yarn
yarn install next@latest If you were using custom routes during its beta phase, migrating to the stable release consists of moving the feature out of module.exports = {
experimental: {},
// rewrites, redirects, and headers are out of `experimental`
async rewrites() {
// ...
},
} |
Beta Was this translation helpful? Give feedback.
-
Guys, how i can remove ".html" extension on rewrite with next js? Edit: Here the solution if you need it
|
Beta Was this translation helpful? Give feedback.
-
When server.js
next.config.js
Note: same scenario when can anyone help with this problem! |
Beta Was this translation helpful? Give feedback.
-
What about SEO? If I redirect example.com/shop/my-products to example.com/my-product doest it creates duplicate content? |
Beta Was this translation helpful? Give feedback.
-
How do Rewrites work under the hood? |
Beta Was this translation helpful? Give feedback.
-
How can I create a custom logic for Ability to modify slugs and reuse the already pre-rendered page has multiple use cases. |
Beta Was this translation helpful? Give feedback.
-
I see that having a custom server the rewrites and redirects features don't apply. I think this would be very useful to be able to do a proper gradually migration, it would be great if rewrites and redirects would work together with custom server. |
Beta Was this translation helpful? Give feedback.
-
Goals
next-routes
and related libraries (and eventual migration path)Background
Next.js has a file system-based router, which supports both static and dynamic routes. This router is normally powerful enough to cover most needs, but sometimes isn't the best fit.
Presently, it is not possible to extend Next.js' router within the framework — this means any custom routing or user-land routing libraries require you to use a custom server, and there is currently no way to incrementally migrate away from libraries like
next-routes
as they still require a custom server.Custom servers were always meant to be reserved for the most advanced or specialized use cases. When you use them, you're partially removed from the framework's pit of success.
When talking with companies and users who use Next.js in production, we found custom servers were most commonly used for redirects and rewrites. While dynamic routes introduced in Next.js 9 cover the majority of use cases, there are still a few cases that have to be covered.
Therefore, it makes sense for Next.js to support these two features — allowing users to remove their usage of a custom server in many cases.
Let's dive into more about what we mean by a redirect, a rewrite, and a header.
Redirects
By redirects, we mean HTTP Redirects (aka URL forwarding). Redirects are most commonly used when a website is reorganized — ensuring search engines and bookmarks are forwarded to their new locations.
Next.js currently does not support redirects as a primitive. As a result, users rely on a custom server or "redirect pages" to implement them. Neither of these solutions are sufficiently ergonomic.
Rewrites
Rewrites are the most commonly used form of custom routing — they're used for dynamic routes (pretty URLs), user-land routing libraries (e.g. next-routes), internationalization, and other advanced use cases.
For example, the route
/user/:id
rendering a specific user's profile page is a rewrite.Rendering your company's about page for both
/about
and/es/acerca
is also a rewrite.We introduced file system-based dynamic routing in Next.js 9 to provide a convention-based way to cover the majority of rewrite use cases. However, some use cases sometimes need more flexibility, especially related to i18n use-cases.
Headers
Headers allow you to set route specific headers like CORS headers,
content-types
, and any other headers that may be needed. They are applied at the very top of the routesProposal
Redirects
Next.js should allow users to create an
async redirects() { ... }
function in theirnext.config.js
. This function would allow you to return an ordered list of redirects.Next.js allows you to specify whether the redirect is permanent or not with the
permanent
field. This is required unless you need to specify thestatusCode
manuallyWhen
permanent
is set totrue
we use a status code of308
and also set aRefresh
header for backwards compatibility with IE11.When
permanent
is set tofalse
we use a status code of307
which is not cached by browsers and signifies the redirect is temporary.Next.js only permits the following status codes:
Please let us know if we missed any redirection status codes.
Shape of a Redirect:
source: string
: the request URL to match, parsed withpath-to-regexp
destination: string
: the destination URL (internal or external)statusCode?: number
: the redirect status codepermanent: boolean
: whether the redirect is permanent (required unless statusCode is provided)<Link>
components should validate the specifiedas
does not match a redirect. If it does, we should render an error client-side.next export
does not have any special behavior for redirects. Meaning, we do not emit redirect pages with<meta http-equiv=refresh content=... />
.Redirects for
next export
-powered websites should be configured manually and varies by hosting provider. These are automatically handled on ZEIT Now as applications.Example Usage
Rewrites
Next.js should allow users to create an
async rewrites() { ... }
function in theirnext.config.js
. This function would allow you to return an ordered list of rewrites.Rewrites always continue down the matching chain, and merge in the last-matched query objects (overwrite previous matches).
Shape of a Rewrite:
source: string
: the request URL to match, parsed withpath-to-regexp
destination: string
: the destination path (internal or external); these rewrites chain down the list in-order unless externalnext export
does not have any special behavior for rewrites. Rewrites fornext export
-powered websites should be configured manually and varies by hosting provider. These are automatically handled on ZEIT Now.Example Usage
Headers
Next.js should allow users to create an
async headers() { ... }
function in theirnext.config.js
. This function would allow you to return an ordered list of headers.Headers always continue down the matching chain, and overwrite any previous matches' headers.
Shape of a Header:
source: string
: the request URL to match, parsed withpath-to-regexp
headers: Array<{ key: string, value: string }>
: an array of header key/value pairsExample Usage
Beta Was this translation helpful? Give feedback.
All reactions