Bird
Raised Fist0
Supabasecloud~20 mins

Protected routes in frontend in Supabase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Supabase Protected Routes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
1:30remaining
How does Supabase handle user session persistence?

Supabase provides a way to keep users logged in across page reloads. What is the main mechanism Supabase uses to persist user sessions in the frontend?

ASupabase requires the developer to manually save the session token in cookies.
BSupabase uses URL query parameters to keep the session active.
CSupabase does not support session persistence; users must log in every time.
DSupabase stores the session token in local storage and automatically refreshes it when needed.
Attempts:
2 left
💡 Hint

Think about where browsers commonly store data that survives page reloads.

❓ Architecture
intermediate
1:30remaining
Which frontend route protection method is best with Supabase?

You want to protect a frontend route so only logged-in users can access it. Which approach works best with Supabase's client library?

ACheck if <code>supabase.auth.getSession()</code> returns a valid session before rendering the route.
BHide the route link in the navigation but allow direct URL access.
CUse server-side rendering to check the session token in cookies before sending the page.
DAlways render the route and redirect users to login only after they try to access protected data.
Attempts:
2 left
💡 Hint

Think about how to verify user login status before showing protected content.

❓ Configuration
advanced
2:00remaining
What is the correct way to redirect unauthenticated users in a React app using Supabase?

In a React app using Supabase, you want to redirect users who are not logged in to the login page when they try to access a protected route. Which code snippet correctly implements this behavior?

Supabase
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { supabase } from '../utils/supabaseClient';

function ProtectedPage() {
  const router = useRouter();

  useEffect(() => {
    async function checkAuth() {
      const session = await supabase.auth.getSession();
      if (!session.data.session) {
        router.push('/login');
      }
    }
    checkAuth();
  }, []);

  return <div>Protected Content</div>;
}
ARemove the <code>async</code> keyword from <code>checkAuth</code> to avoid errors.
BChange <code>router.push('/login')</code> to <code>window.location.href = '/login'</code> for better routing.
CReplace <code>if (!session)</code> with <code>if (!session.data.session)</code> to correctly check the session object.
DCall <code>checkAuth()</code> outside of <code>useEffect</code> to run it immediately.
Attempts:
2 left
💡 Hint

Check the structure of the object returned by supabase.auth.getSession().

❓ security
advanced
1:30remaining
What security risk exists if protected routes rely only on frontend checks with Supabase?

If you protect routes only by checking user login status on the frontend with Supabase, what is the main security risk?

AUsers can bypass frontend checks by disabling JavaScript or modifying client code, gaining unauthorized access to data.
BSupabase will automatically block unauthorized API calls, so there is no risk.
CFrontend checks slow down the app and cause session timeouts.
DThere is no risk because Supabase encrypts all frontend data.
Attempts:
2 left
💡 Hint

Think about what users can do with their browsers and client code.

🧠 Conceptual
expert
2:00remaining
How does Supabase's real-time subscription affect protected routes in frontend apps?

Supabase supports real-time data subscriptions. When using protected routes, what must you ensure about these subscriptions to maintain security?

ADisable real-time subscriptions on protected routes to avoid security risks.
BEnsure subscriptions are only established after confirming the user session is valid to prevent unauthorized data streaming.
CUse public subscriptions for all users and filter data on the client side to improve performance.
DSubscriptions automatically respect frontend route protection, so no extra checks are needed.
Attempts:
2 left
💡 Hint

Consider when and how subscriptions connect to the backend.

Practice

(1/5)
1. What is the main purpose of protected routes in a frontend application using Supabase?
easy
A. To allow only logged-in users to access certain pages
B. To speed up page loading times
C. To store user data permanently
D. To change the app's theme automatically

Solution

  1. Step 1: Understand what protected routes do

    Protected routes restrict access to certain pages so only authorized users can see them.
  2. Step 2: Connect with Supabase session usage

    Supabase sessions help check if a user is logged in, enabling route protection.
  3. Final Answer:

    To allow only logged-in users to access certain pages -> Option A
  4. Quick Check:

    Protected routes = restrict access to logged-in users [OK]
Hint: Protected routes block access unless user is logged in [OK]
Common Mistakes:
  • Thinking protected routes speed up loading
  • Confusing route protection with data storage
  • Assuming protected routes change app appearance
2. Which of the following is the correct way to check if a user is logged in using Supabase in frontend code?
easy
A. const user = supabase.auth.getUser()
B. const user = supabase.session()
C. const user = supabase.auth.session()
D. const user = supabase.auth.getSession()

Solution

  1. Step 1: Identify Supabase method for session retrieval

    Supabase's current method to get session info is auth.getSession(), which returns user session data.
  2. Step 2: Compare options with official API

    Options A, B, and C are outdated or incorrect method names; only getSession() is valid.
  3. Final Answer:

    const user = supabase.auth.getSession() -> Option D
  4. Quick Check:

    Use auth.getSession() to check login [OK]
Hint: Use supabase.auth.getSession() to get current user session [OK]
Common Mistakes:
  • Using deprecated methods like auth.session()
  • Calling supabase.session() which does not exist
  • Confusing getUser() with getSession()
3. Given this React snippet using Supabase, what will happen if the user is not logged in?
const session = supabase.auth.getSession();
if (!session) {
  navigate('/login');
} else {
  showDashboard();
}
medium
A. The dashboard is shown regardless
B. An error is thrown because getSession() is async
C. The user is redirected to the login page
D. Nothing happens; the page stays the same

Solution

  1. Step 1: Understand getSession() behavior

    supabase.auth.getSession() is an asynchronous function returning a Promise, so calling it without await assigns a Promise object to session, not session data.
  2. Step 2: Analyze the code flow

    A Promise object is truthy, so if (!session) evaluates to false, and showDashboard() executes regardless of login status.
  3. Final Answer:

    The dashboard is shown regardless -> Option A
  4. Quick Check:

    Async getSession() without await returns truthy Promise [OK]
Hint: Remember to await async getSession() calls [OK]
Common Mistakes:
  • Treating async getSession() as synchronous
  • Assuming session is null if user not logged in
  • Ignoring Promise returned by getSession()
4. You wrote this code to protect a route but it redirects even logged-in users to login:
const { data: session } = supabase.auth.getSession();
if (!session) {
  window.location.href = '/login';
}

What is the main issue?
medium
A. session is always truthy even if user is logged out
B. window.location.href cannot redirect pages
C. getSession() is asynchronous and must be awaited
D. You must use supabase.auth.getUser() instead

Solution

  1. Step 1: Check getSession() usage

    supabase.auth.getSession() returns a Promise and must be awaited or handled asynchronously to get session data.
  2. Step 2: Understand destructuring without await

    Destructuring data from a Promise without await results in undefined or incorrect values, so session is not properly checked.
  3. Final Answer:

    getSession() is asynchronous and must be awaited -> Option C
  4. Quick Check:

    Always await async getSession() calls [OK]
Hint: Always await async Supabase calls to get real data [OK]
Common Mistakes:
  • Not awaiting async functions
  • Thinking window.location.href can't redirect
  • Using getUser() instead of getSession() incorrectly
5. You want to protect a React page so only logged-in users can see it. Which approach correctly implements this using Supabase's session and React hooks?
function ProtectedPage() {
  const [session, setSession] = React.useState(null);

  React.useEffect(() => {
    const getSession = async () => {
      const { data } = await supabase.auth.getSession();
      setSession(data.session);
      if (!data.session) {
        navigate('/login');
      }
    };
    getSession();
  }, []);

  if (!session) return <p>Loading...</p>;
  return <div>Welcome to protected content!</div>;
}
hard
A. The navigate call should be outside the async function
B. This code correctly protects the page by redirecting unauthenticated users
C. The code should call supabase.auth.getUser() instead of getSession()
D. The session state should be initialized with supabase.auth.getSession() synchronously

Solution

  1. Step 1: Analyze async session retrieval in useEffect

    The code correctly uses an async function inside useEffect to get the session and update state.
  2. Step 2: Check redirect logic for unauthenticated users

    If no session exists, the code calls navigate('/login') to redirect users, protecting the page.
  3. Step 3: Confirm loading state handling

    While session is null, it shows a loading message, preventing content flash before redirect.
  4. Final Answer:

    This code correctly protects the page by redirecting unauthenticated users -> Option B
  5. Quick Check:

    Async session check + redirect = protected route [OK]
Hint: Use async useEffect with redirect on no session [OK]
Common Mistakes:
  • Using getUser() instead of getSession() for session check
  • Calling navigate outside async context incorrectly
  • Initializing session state synchronously causing errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard