next js redirect to page
Next.js
Documentation
API Reference
Redirects
Redirects allow you to redirect an incoming request path to a different destination path.
Redirects are only available on the Node.js environment and do not affect client-side routing.
To use Redirects you can use the redirects key in next.config.js :
Redirects are checked before the filesystem which includes pages and /public files.
When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration:
Path Matching
Path matches are allowed, for example /old-blog/:slug will match /old-blog/hello-world (no nested paths):
Wildcard Path Matching
To match a wildcard path you can use * after a parameter, for example /blog/:slug* will match /blog/a/b/c/d/hello-world :
Regex Path Matching
To match a regex path you can wrap the regex in parentheses after a parameter, for example /post/:slug(\\d<1,>) will match /post/123 but not /post/abc :
Header, Cookie, and Query Matching
To only match a redirect when header, cookie, or query values also match the has field can be used. Both the source and all has items must match for the redirect to be applied.
has items have the following fields:
Redirects with basePath support
When leveraging basePath support with redirects each source and destination is automatically prefixed with the basePath unless you add basePath: false to the redirect:
Redirects with i18n support
When leveraging i18n support with redirects each source and destination is automatically prefixed to handle the configured locales unless you add locale: false to the redirect. If locale: false is used you must prefix the source and destination with a locale for it to be matched correctly.
In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the statusCode property instead of the permanent property, but not both. Note: to ensure IE11 compatibility a Refresh header is automatically added for the 308 status code.
How to redirect all pages to /login if no user found in session? Looking for examples. #14945
Is there a good example (maybe from Next.js examples) that shows how to redirect all pages to a /login page if no user found in the session?
I checked some examples but the with-iron-session redirects to /login from within the page, I’m looking for a more global way to redirect and maybe opt-out pages (ie. About us) that don’t need authentication.
I also see the with-firebase-authentication is also using something similar at page level:
There the userUser hook will redirect in case not user is found.
Would this possible to do, let’s say with the userHook being called in _app.js and redirect all pages from there when no user is found? And possibly pass a param from an About us page so the auth check can be skipped?
I’m just looking for ideas 👍
Replies
Assuming you’re not using a custom server and you’re using context or redux and dealing with page-level authentication, then there really isn’t a one-size-fits-all/great way to handle global auth checks if you want to keep site-wide ASO (automatic static optimization) and quick responses/interaction.
Current options are (the examples below include redux and cookie-session):
1.) Check in getInitialProps within a custom _app.
This blocks the entire app from loading, opts out of ASO, and results in a slower TTFB/FCP. You’ll also have to keep a blacklist of which routes require auth and which ones don’t. This can become quite a nuisance when dealing with hundreds-thousands of dynamic routes.
_app.js
2.) Check in page-level getServerSideProps/getStaticProps.
Similar to the above, however, this will keep ASO and doesn’t render block the entire app, but it’ll still render block the page from loading (and result in a slower TTFB/FCP if using getServerSideProps). In addition, it’ll need to be replicated across any authenticated pages, and as of writing is currently a RFC.
Settings.js (an authenticated page)
User Settings Page
3.) Check in a reusable page-level HOC (higher-order component).
This keeps ASO and results in a quicker TTFB/FCP because it doesn’t render block any pages from loading, so you’ll have to utilize some placeholders (like skeletons or spinners). It also checks for a logged-in session once and only once without any additional logic. The disadvantage of this is that your auth pages won’t be SSR’d, nor can they previewable/pre-rendered. It also requires an additional request (additional request other than the requested page) in a custom _app’s useEffect lifecycle, and all redirects will happen on the client-side only. While this results in a quicker TTFB/FCP and is reusable for any other auth pages, it, unfortunately, results in a slower FID.
_app.js
Reusable withAuthentication HOC (like a middleware component):
Settings.js (authenticated page)
User Settings Page
Until option 2 becomes available, I’d recommend option 3 (this is what I’m currently using). For simple authentication logic, option 1 is like taking a bulldozer to the entire app, which really isn’t necessary nor ideal. Option 1 also doesn’t play well with redux since the state is initially empty during a page load. So if you set some state to redux on the server, then redirect on the server, then unfortunately the state will be reset again.
Next.js Redirect from / to another page
I’m new in Next.js and I’m wondering how to redirect from start page ( / ) to /hello-nextjs for example. Once user loads a page and after that determine if path === / redirect to /hello-nextjs
In react-router we do something like:
11 Answers 11
Edit : Next.js >= 10
From Next.js 10 you can do server side redirects (see below for client side redirects) with a redirect key inside getServerSideProps or getStaticProps :
In next.js you can redirect after the page is loaded using Router ex :
If you want to prevent the flashing before the redirect you can use a simple trick :
I would say that in general is not a good/elegant approach to do client redirects when you can use next.config.js redirects or even better use conditional render of components.
I have create a simple repo with all the examples above here.
Caveat
First, you should asses whether you need client-side redirection (within React), server-side redirection (301 HTTP response) or server-side redirection + authentication (301 HTTP response but also having some logic to check authentication).
Server-side redirection are tempting, in particular when you want to «secure» private pages, but you should assess whether you really need them. Usually, you don’t. They induce unexpected complexity, like managing auth token and refresh token. Instead, you may want to add a gateway server, a reverse proxy or whatever upfront server to your architecture for instance to handle those kind of checks.
Keep in mind that Next.js are just React app, and using Next.js advanced features like SSR comes at a cost that should be justified in your context.
Next 9.4 answer
Hi, here is an example component working in all scenarios:
The answer is massive, so sorry if I somehow break SO rules, but I don’t want to paste a 180 lines piece of code. There is no easy pattern to handle redirection in Next, if you want to both support SSR and static export.
The following scenarios each need a specific pattern:
Next 9.5 update
As stated by @Arthur in the comments, 9.5 also include the possibilities to setup redirects in next.config.js. The limitations of this feature are not yet clear to me, but they seem to be global redirections, e.g. when you need to move a page or to allow access only during a limited period. So they are not meant to handle authentication for instance, because they don’t seem to have access to the request context. Again, to be confirmed.
Next 10 new doc update
This solution is specific to redirection depending on authentication.
You may also want to check the approach documented in this ticket based on how Vercel’s dashboard works (at the time of writing), that prevents flash of unauthenticated content
Next 10.2 header and cookies based rewrites update
Next 10.2 introduces Rewrites based on headers and cookies. That’s a great way to redirect server-side, based on the presence of an authentication cookie or header.
However, keep in mind that this is not a secure redirection. User can alter their request headers with a false token. You still need a gateway, a reverse proxy or an upfront server to actually check token validity and correctly set the headers.
Edit: note that the URL won’t change. A rewrite points an URL to an existing page of your application, without changing the URL => it allows you to have «virtual» URLs.
Old answer (works, but will have a messy static render)
Semi-official example
It handles both server side and client side. The fetch call is the one that actually get the auth token, you might want to encapsulate this into a separate function.
What I would advise instead
1. Redirect on server-side render (avoid flash during SSR)
This is the most common case. You want to redirect at this point to avoid the initial page flashing on first load.
2. Redirect in componentDidMount (useful when SSR is disabled, eg in static mode)
This is a fallback for client side rendering.
I could not avoid flashing the initial page in static mode add this point, because you can’t redirect during the static build, but it seems better than the usual approaches. I’ll try to edit as I make progress.
Sergio XalambrГ
When working with Next.js is super common to reach the point you need to redirect the user to another page, maybe because the user tried to access a private page or the user tried to access an old page.
This could be done in multiple ways, the most popular is to use an HTTP Redirect to achieve this, or Router.replace if the page is accessed client-side.
While that works just fine is not ideal, for the first render the user will need an extra request to the server to get the correct page, but it turns out you already know the page the user is going to request since you are setting the HTTP Redirect, why not then render the correct page at straightaway?
Server-Side Code
This way to set the redirect involves both Server and Client-side code, let’s start with the server-side code. Let’s say we have two pages, a /login and a /private page, both in our pages directory like this.
Note: readCookies is a fake function that should read the cookies from the request headers and return an object with them.
Now in our PrivatePage component, we can render the login directly.
With this when the user access /private and doesn’t have the session cookie, it will instead receive the HTML of the login page.
Note: We used a dynamic import to avoid loading the code of LoginPage if it’s not going to be used. This will save the user a few kB.
Client-Side Code
Let’s go to the Client-Side part of our redirect, the user accessed /private and received the login page HTML, that’s great but the user still sees /private in their browser. Let’s fix that.
Next comes with a module called next/router which lets us change the route programmatically, we could use that to navigate to another page without requiring the user to click a link.
Let’s add an effect in our PrivatePage to change the URL.
The function Router.replace receives the href which is the actual route inside Next (aka the page) and the as which is the route we want to show to the user. Those two let use tell Next.js to use our already loaded PrivatePage but disguise it as /login in the browser.
Final Words
This is the best approach to implement redirects using Next, I learned it while I was working at ZEIT the creators of the framework and is how I implemented a few redirects back there.
This page was rendered at Friday, September 17, 2021 at 4:09:25 PM
How to redirect? #4931
Comments
popuguytheparrot commented Aug 9, 2018
render() <
if(!auth) Router.push(‘login’)
>
Error: No router instance found.
You should only use «next/router» inside the client side of your app.
how do redirect do right?
The text was updated successfully, but these errors were encountered:
We are unable to convert the task to an issue at this time. Please try again.
The issue was successfully created but we are unable to update the comment at this time.
klujanrosas commented Aug 9, 2018 •
The wiki has an entry about this subject.
For a more real world example, please see with-apollo-auth example.
From what I’ve seen you should post any future questions not related to actual issues to Next’s Spectrum Chat instead.
popuguytheparrot commented Aug 10, 2018
@klujanrosas Your example doesnt work in my case
swve commented Feb 6, 2019
How redirecting can be so hard with nextjs >:(
sergiodxa commented Feb 6, 2019 •
Check the code of this module https://github.com/matthewmueller/next-redirect/ it’s actually quite simple, you should redirect in getInitialProps to avoid rendering and fetching unnecessary data.
jgillich commented Mar 23, 2019
Maybe some details would be great, instead of just downvoting. Because the example works completely fine for me.
omonk commented Apr 10, 2019
I believe this is a difference in getInitialProps signature for _app.js and normal pages
seanconnollydev commented May 14, 2019 •
@sergiodxa @jgillich I am doing something very similar to the implementation in next-redirect but after initiating a redirect on the client (via window.location.href=»» where the string is the redirect url), getInitialProps still returns and the page still tries to render briefly before the browser redirects. Do you see the same behavior? Any tips on preventing that behavior?
lifeiscontent commented Jul 12, 2019
ccemeraldeyes commented Jul 18, 2019
I am not sure why this got closed when it clearly does not answer the question for so many people.
Timer commented Jul 18, 2019 •
Issuing a side effect during rendering is not a standard React practice.
This can easily become problematic in many scenarios, especially if Next.js ever starts optimistically rendering hidden trees for navigation.
You should avoid redirecting client-side within getInitialProps for the same reason. While this pattern currently works in practice, the patterns listed below are more encouraged.
Redirects are a side effect, and should occur as so within your component’s events:
For a functional component:
Please open a new thread on our Spectrum if you have any questions or need guidance.