Which of the following best explains why authentication is crucial in web applications?
Think about what happens if anyone can access private data without verifying who they are.
Authentication confirms the identity of users, ensuring that only those with permission can access sensitive parts of the app. This protects user data and application integrity.
Consider a Next.js page that checks if a user is logged in before showing content. What is the expected behavior if the user is not authenticated?
Think about how apps protect private pages from users who haven't signed in yet.
Protected pages usually redirect unauthenticated users to a login page to ensure only authorized users can see the content.
Given this simplified Next.js component code, what will be rendered if user is null?
import { useState, useEffect } from 'react'; export default function Dashboard() { const [user, setUser] = useState(null); useEffect(() => { // Simulate fetching user data setTimeout(() => setUser(null), 1000); }, []); if (!user) { return <p>Please log in to view your dashboard.</p>; } return <p>Welcome back, {user.name}!</p>; }
Check what the component returns when user is null.
The component returns the message asking the user to log in because user is null. The welcome message only shows if user has a value.
Choose the code that correctly uses getServerSideProps to redirect unauthenticated users to the login page.
Remember that getServerSideProps must return a redirect object to redirect users.
Option D correctly returns a redirect object when the user is not authenticated. Other options either misuse redirect or return incorrect props.
Examine the code below. Why does it cause a runtime error when the page loads?
import { useState, useEffect } from 'react'; export default function Profile() { const [user, setUser] = useState(); useEffect(() => { fetch('/api/user') .then(res => res.json()) .then(data => setUser(data.user)); }, []); return <p>Hello, {user.name}!</p>; }
Think about what happens before the fetch finishes and user is set.
The component tries to read user.name before user has a value, causing a TypeError because you cannot read properties of undefined.