private route in next js

Solutions on MaxInterview for private route in next js by the best coders in the world

showing results for - "private route in next js"
Alberto
22 Aug 2019
1/// Dashboard
2import React from 'react';
3import withPrivateRoute from '../components/withPrivateRoute';
4
5const Dashboard = () => {
6  return <div>This is a Dashboard page which is private.</div>;
7};
8
9Dashboard.getInitialProps = async props => {
10  console.info('##### Congratulations! You are authorized! ######', props);
11  return {};
12};
13
14export default withPrivateRoute(Dashboard);
15
16///////////////////////////////////////////////////////////////////
17///////////////////////////////////////////////////////////////////
18///////////////////////////////////////////////////////////////////
19///////////////////////////////////////////////////////////////////
20
21/////WrappedComponent //////////
22
23
24import React from 'react';
25import Router from 'next/router';
26
27const login = '/login?redirected=true';
28
29const checkUserAuthentication = () => {
30  return { auth: null };
31};
32
33export default WrappedComponent => {
34  const hocComponent = ({ ...props }) => <WrappedComponent {...props} />;
35
36  hocComponent.getInitialProps = async (context) => {
37    const userAuth = await checkUserAuthentication();
38
39    if (!userAuth?.auth) {
40      if (context.res) {
41        context.res?.writeHead(302, {
42          Location: login,
43        });
44        context.res?.end();
45      } else {
46        Router.replace(login);
47      }
48    } else if (WrappedComponent.getInitialProps) {
49      const wrappedProps = await WrappedComponent.getInitialProps({...context, auth: userAuth});
50      return { ...wrappedProps, userAuth };
51    }
52
53    return { userAuth };
54  };
55
56  return hocComponent;
57};
Emiliano
14 Mar 2018
1export async function getServerSideProps({ req, res }) {
2  const { Auth } = withSSRContext({ req })
3  try {
4    const user = await Auth.currentAuthenticatedUser()
5    return {
6      props: {
7        authenticated: true,
8        username: user.username
9      }
10    }
11  } catch (err) {
12    res.writeHead(302, { Location: '/profile' })
13    res.end()
14  }
15  return {props: {}}
16}
17
18export default Protected