protected route in next js code example
Example 1: next js protected routes
export async function getServerSideProps({ req, res }) {
const { Auth } = withSSRContext({ req })
try {
const user = await Auth.currentAuthenticatedUser()
return {
props: {
authenticated: true,
username: user.username
}
}
} catch (err) {
res.writeHead(302, { Location: '/profile' })
res.end()
}
return {props: {}}
}
export default Protected
Example 2: private route in next.js
import React from 'react';
import withPrivateRoute from '../components/withPrivateRoute';
const Dashboard = () => {
return <div>This is a Dashboard page which is private.</div>;
};
Dashboard.getInitialProps = async props => {
console.info('##### Congratulations! You are authorized! ######', props);
return {};
};
export default withPrivateRoute(Dashboard);
import React from 'react';
import Router from 'next/router';
const login = '/login?redirected=true';
const checkUserAuthentication = () => {
return { auth: null };
};
export default WrappedComponent => {
const hocComponent = ({ ...props }) => <WrappedComponent {...props} />;
hocComponent.getInitialProps = async (context) => {
const userAuth = await checkUserAuthentication();
if (!userAuth?.auth) {
if (context.res) {
context.res?.writeHead(302, {
Location: login,
});
context.res?.end();
} else {
Router.replace(login);
}
} else if (WrappedComponent.getInitialProps) {
const wrappedProps = await WrappedComponent.getInitialProps({...context, auth: userAuth});
return { ...wrappedProps, userAuth };
}
return { userAuth };
};
return hocComponent;
};