Exercises: Security Risks with Client Components πŸ”‘

Now that you understand the security risks with Client Components, let's get to the exercise!

Your Mission πŸ›‘οΈ

  1. Convert page.tsx to a Server Component.
  2. NEXT_PUBLIC_DUMMY_API_KEY should not be exposed to the Browser.
  3. 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:

  1. page.tsx is a Server Component.
  2. 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:

  1. Click on "Client Component" and you'll see:

    app/page.tsx
    Client Component
    {"data":"data from Client Component API"}
    
  2. Click on "Server Component" and you'll get:

    app/server/page.tsx
    Server 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.

Check it out here

Stay tuned!

The Course has launched in Early Access! πŸŽ‰

The Modern Full Stack Next.js Course has launched in Early Access with over 50% off!
Feedback