score:27
with next.js (and any universal react rendering) your code is executing in two different environments. first in node (on the server) and then in a browser. next does some work to provide unified functions that run in both these environments but they're very different. next can't and doesn't keep this from you. it seems like you just loaded a page in your browser but here's a little more detail on what's really going on…
on the client/browser:
- type url in the address bar (localhost:3000 or whatever), press enter.
- get request goes out to the server (node).
on the server/node:
- get request comes in.
- node gives you a request and a response object.
- maybe you have some express routing/middleware.
- at some point next's
render()
function is called with the request and response objects. - next runs
getinitialprops
and passes in the request/response. - react
rendertostring()
is called which calls the following react lifecycle methods:constructor()
componentwillmount()
render()
- react creates a string of html that gets sent to the client.
^ this is node. you can't access window
, you don't have fetch
, and you can't use the next router. those are browser things.
back on the client:
- html is downloaded and rendering begins.
- links to js/css files in the html are downloaded/run.
- this includes js code compiled by next.
- react
render()
is run which associates the downloaded html (the dom) with a react virtual dom. the following react lifecycle methods will run:constructor()
componentwillmount()
render()
componentdidmount()
- all other lifecycle methods (updates) will run when props/state change.
^ this is the browser. you have window
, you have fetch
, you can use the next router. now you don't have the node request/response but that seems to catch people up less.
ref: component lifecycle
score:0
i found this https://www.npmjs.com/package/nextjs-redirect to be very simple and solved the issue for both client and server side.
pages/donate.js
import redirect from 'nextjs-redirect'
export default redirect('https://paypal.me')
score:1
to make sure the page never render, we need to add await new promise(() => {})
to end. the promise no needed resolve anything.
home.getinitialprops = async ({res}) => {
if(res) {
res.writehead(302, {location: '/dashboard'});
res.end();
} else {
// window.location.href = '/dashboard';
// or with spa redirect
router.push('/dashboard');
}
await new promise(() => {});
return {}
}
score:2
next/router is not available on the server that's way you get an error saying that router not found, next/router can only be used on the client side.
for you to redirect a user inside getinitialprops in the server you can use:
getinitialprops({server,res}){
if(server)
res.redirect('/');
else
router.push('/');
}
score:3
you can redirect from getinitialprops()
like this:
import router from 'next/router'
static getinitialprops = (ctx) => {
// on server
if(typeof window === 'undefined'){
res.writehead(302, {location: '/dashboard'})
res.end()
} else {
// on client
router.push('/dashboard')
}
return {}
}
score:4
the way works like @shi said, but there is not server
in getinitialprops. instead of that, there should check window
:
getinitialprops({res}){
if(typeof window === 'undefined')
res.redirect('/');
else
router.push('/');
}
Source: stackoverflow.com
Related Query
- Redirect shows the sign in page partially before redirecting in next js react
- Call a Python script from React with next routing and a node.js server
- Redirecting from getInitalProps in React/Next.js
- React + Next : Not sending cookies from server-side to backend
- React redirecting to 404 Route from id-based Route
- Using react and react-bootstrap, stop components from moving to next row when window is resized to be smaller
- Using context to pull from a store in a React page in next
- Passing data from a react form to expressJS and also redirecting to the PayuMoney website to make payment
- React Routing V6 problem, redirecting to another path: '/contact' the content from <Contact /> get updated above nav instead of separate page
- React / Next - importing component from external library cause : Element type is invalid: expected a string or a class/function but got: undefined
- React bootstrap table next convert column toggle from button list to select dropdown?
- Using values from previously dispatched action in the next action in React and Redux
- Accessing data passed from NavLink after redirecting from home page to a specific page using react router
- react router link to the next view only if I get the response from the api request
- React Router Redux - Infinite loop when redirecting from IndexRoute
- React - Updating parameters for function calls by taking data from one component and passing it to the next is lagging by one step
- React Infinite scroll, i'm trying to append the data received from the api call to the next onScroll, it just replaces the last data
- Redirecting from one Page to Another in React
- Error Running React Native App From Terminal (iOS)
- React component initialize state from props
- How to update React Context from inside a child component?
- React hooks: accessing up-to-date state from within a callback
- React js change child component's state from parent component
- Rendering React Components from Array of Objects
- Get version number from package.json in React Redux (create-react-app)
- Call a React component method from outside
- Call a React component method from outside
- React display line breaks from saved textarea
- Functions are not valid as a React child. This may happen if you return a Component instead of from render
- React Hook : Send data from child to parent component
More Query from same tag
- Trying to change react Carousel into class component
- Babel plugin (babel-plugin-module-alias) with React Native
- How to update key values behalf of Id's
- Add text over images next to each other with react inline styles
- How can i use combineReducers and reduceReducers together?
- Not able to pass authentication header in axios along with bodyFormData
- How to set local storage in cypress
- Reagent :component-did-mount hook not called with meta-annotated component function
- WalletConnect fails to get bundled with vite
- Can I change other pieces of state in a Recoil Atom Effect
- React not redirecting after first login. But redirects after forcefully redirecting and doing a login action again
- How to allow certain combinations of props in React Typescript?
- React Form returning null values with useRef() hook
- Is it bad to use complex objects in react state?
- How to I modify color in an SVG in React?
- React changing state in Parent , does render calls for all its children and sub-children as iteration?
- ReactJS re-render is not applied on CSS
- define generic redux action creator in typescript
- React Hook Form doesn´t display errors (TypeError: Cannot read properties of undefined (reading 'name')
- How to add a route to image in React.js
- Redux-thunk "dispatch is not a function"
- Avoiding binding in Render while maintaining context from Parent Component
- React - pass SCSS "object" as property
- Todo list Reverse state to false on click onclick
- Apolloclient with more than 2 ApolloLinks
- How to structute the data properly in firestore?
- How can I map an array of dicts inside a React return statement?
- How to query a firestore database using react
- Fetching data from firestore collection in react js
- Testing async custom hooks that useEffect with react-hooks-testing-library