Exercises: Security Risks with Client Components π
Now that you understand the security risks with Client Components, let's get to the exercise!
Your Mission π‘οΈ
- Convert
page.tsx
to a Server Component. NEXT_PUBLIC_DUMMY_API_KEY
should not be exposed to the Browser.- Double-check your work: Inspect the page in the browser by clicking on Inspect Element (Chrome), hit the source tab, look into webpack internals. If you can't find
page.tsx
, you've nailed it!
Acceptance Criteria
An acceptance criteria is a set of criteria that must be met for a project to be considered complete. In this case, we need to ensure that:
page.tsx
is a Server Component.NEXT_PUBLIC_DUMMY_API_KEY
is not exposed to the Browser.
Let's Get Coding!
Coding Environment
Security: Exposing API KeysOpen in New Tab
Now, let's break it down:
-
Click on "Client Component" and you'll see:
app/page.tsxClient Component {"data":"data from Client Component API"}
-
Click on "Server Component" and you'll get:
app/server/page.tsxServer Component {"data":"data from Server Component API"}
Here's the kicker: If we leave our API keys exposed in Client Components, we're basically leaving our house keys π under the doormat. Anyone who knows where to look can find them!
So, why are Server Components our new best friends?
Think of them as a secure vault π inside your bank. You can store your valuables (like API keys) there, and only authorized personnel (your server) can access them. Clients can request information, but they never get to see inside the vault.
Sure, you could set up a separate API to handle this, but Server Components make it smoother. It's like having a built-in security system instead of hiring a separate security guard.
By understanding both the problem and the solution, you'll be better equipped to build secure Next.js applications that interact safely with private APIs.
There's a ton more to unpack here as we are barely scratching the surface but don't worry β we'll dive deep into all this goodness in my upcoming Next.js course . You can sign up for the course in Early Access here .
The course is a whopping 50% off for Early Access members.
Stay tuned!