I have made authentication, I use express-sessions and passports. so when the user login will save the session on the server. to access the route requires this session. the session that I created I saved it in redux store and when I checked getInitialProps
there was redux store
I want to use this as a reference if the user is not logged in, it will redirect to the login page.
, In this case, the URL has changed but I can't access.
This page is 't working localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
I cant use 'next/router'
because Router only can access on the client.
_app.js
import App, { Container } from 'next/app'
import React from 'react'
import withReduxStore from '../lib/with-redux-store'
import { Provider } from 'react-redux'
import { MuiThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import JssProvider from 'react-jss/lib/JssProvider';
import getPageContext from '../lib/getPageContext';
import '../index.css';
class MyApp extends App {
static async getInitialProps(something){
const { Component, router, ctx } = something;
const initialState = ctx.reduxStore.getState();
if(Object.keys(initialState.auths.admin).length === 0){
ctx.res.writeHead(302, {
Location: '/login'
});
ctx.res.end();
res.finished = true;
return {}
}
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
constructor() {
super();
this.pageContext = getPageContext();
}
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles && jssStyles.parentNode) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
render() {
const { Component, pageProps, reduxStore } = this.props
return (
<Container>
<Provider store={reduxStore}>
<JssProvider
registry={this.pageContext.sheetsRegistry}
generateClassName={this.pageContext.generateClassName}
>
<MuiThemeProvider
theme={this.pageContext.theme}
sheetsManager={this.pageContext.sheetsManager}
>
<CssBaseline />
<Component
pageContext={this.pageContext}
{...pageProps} />
</MuiThemeProvider>
</JssProvider>
</Provider>
</Container>
)
}
}
export default withReduxStore(MyApp)
The error “too many redirects” means that the website keeps being redirected between different addresses in a way that will never complete. Often this is the result of competing redirects, one trying to force HTTPS (SSL) and another redirecting back to HTTP (non-SSL), or between www and non-www forms of the URL.
In this case, the user will be redirected to '/login' in an infinity loop if Object.keys(initialState.auths.admin).length === 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.