0
0
NextJSframework~10 mins

Role-based access patterns in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the user has the 'admin' role.

NextJS
if (user.roles.includes([1])) {
  return <AdminPanel />;
} else {
  return <AccessDenied />;
}
Drag options to blanks, or click blank then click option'
A'user'
B'guest'
C'admin'
D'moderator'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a role that does not exist in the roles array.
Forgetting to use quotes around the role string.
2fill in blank
medium

Complete the code to redirect users without the 'editor' role to the home page.

NextJS
if (!user.roles.includes([1])) {
  router.push('/');
}
Drag options to blanks, or click blank then click option'
A'admin'
B'guest'
C'viewer'
D'editor'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong role string.
Missing the negation operator (!) before includes.
3fill in blank
hard

Fix the error in the code that checks if the user has any role from a list.

NextJS
const hasAccess = roles.some(role => user.roles.[1](role));
Drag options to blanks, or click blank then click option'
Afind
Bincludes
Cfilter
Dmap
Attempts:
3 left
💡 Hint
Common Mistakes
Using find() which returns an element or undefined, not a boolean.
Using map() which transforms arrays but does not check membership.
4fill in blank
hard

Fill both blanks to create a higher-order component that restricts access based on roles.

NextJS
function withRole(Component, [1]) {
  return function Wrapped(props) {
    const user = useUser();
    if (!user.roles.[2](role => [1].includes(role))) {
      return <AccessDenied />;
    }
    return <Component {...props} />;
  };
}
Drag options to blanks, or click blank then click option'
AallowedRoles
Bsome
Cfilter
Devery
Attempts:
3 left
💡 Hint
Common Mistakes
Using every() instead of some(), which requires all roles to match.
Using filter() which returns an array, not a boolean.
5fill in blank
hard

Fill all three blanks to implement server-side role check in Next.js getServerSideProps.

NextJS
export async function getServerSideProps(context) {
  const session = await getSession(context);
  if (!session || !session.user.roles.[1](role => role === [2])) {
    return {
      redirect: {
        destination: [3],
        permanent: false,
      },
    };
  }
  return { props: {} };
}
Drag options to blanks, or click blank then click option'
Asome
B'admin'
C'/login'
Devery
Attempts:
3 left
💡 Hint
Common Mistakes
Using every() which requires all roles to be 'admin'.
Redirecting to the wrong path.