Access environment variables safely on the server.
NextJS
exportdefaultfunction ServerOnlyLogic() {
const secret = process.env.SECRET_KEY;
return <div>Secret is hidden from browser</div>;
}
Sample Program
This server component reads a text file on the server and shows its content inside a <pre> block. The file reading happens only on the server, so the browser never sees the file system code.
B. onClick handlers are not allowed in server components
C. useState cannot be used in server components
D. No error, code works fine
Solution
Step 1: Check React hooks usage in server components
useState is a client-side hook and cannot be used in server components.
Step 2: Check event handlers in server components
onClick handlers require client-side JavaScript and are not supported in server components.
Final Answer:
Both A and B -> Option A
Quick Check:
useState + onClick invalid in server components [OK]
Hint: No React hooks or event handlers in server components [OK]
Common Mistakes:
Using useState in server components
Adding client event handlers in server components
Assuming server components can handle user events
5. You want to fetch data from a database and display it in a Next.js app. Which approach best uses server components to improve performance and security?
hard
A. Fetch data in the browser using fetch API directly
B. Fetch data inside a client component using useEffect
C. Fetch data inside a server component and pass it as props to a client component
D. Fetch data in a client component and store it in localStorage
Solution
Step 1: Understand server component advantages
Server components can securely fetch data on the server, avoiding exposing secrets or extra client JS.
Step 2: Use server component to fetch and pass data
Fetching data in server component and passing it as props to client components optimizes performance and security.
Final Answer:
Fetch data inside a server component and pass it as props to a client component -> Option C
Quick Check:
Server fetch + props passing = best practice [OK]
Hint: Fetch data server-side, then pass to client components [OK]
Common Mistakes:
Fetching data only on client causing slower load
Exposing secrets by fetching in client
Storing sensitive data in localStorage
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.