I
I
Ivan Derbenchenko2021-09-29 10:51:16
React
Ivan Derbenchenko, 2021-09-29 10:51:16

How to correctly organize authorization in NextJS?

Hello everyone!)
Just started learning NextJS.
In general: you need to hide all pages for an unauthorized user, and after registration, you can actually use the application normally ...
Requests to the database are made through axios. There is a separate API class with presets.
1) How to do it correctly, do a check in the _app.js component by the isAuth flag:

export default function App({ Component, pageProps }) {
    const store = useStore(pageProps.initialReduxState);
    const {isAuth} = store.getState().user;
    return (
        <>
            <Provider store={store}>
            <HeadApp/>
                {isAuth?
                <Container>
                    <Component {...pageProps} />
                </Container>
                :
                <Auth/>
                 }
            </Provider>

        </>
    );
}

or make a separate page along the /auth path, and in each component check this flag and do a redirect in case of false?
2) How to store tokens? On the version with a regular React application (without a framework), I stored tokens in localStorage, so that if the page reloads, I can get tokens from there and check if they are rotten or not, if so, update them, if not, just authorize. Next, as I already understood, does not have access to localStorage (gives an error), since it processes the code on the server.

Authorization by JWT.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question