0
0
NextJSframework~30 mins

Server-only modules in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Server-only Modules in Next.js
📖 Scenario: You are building a Next.js app that fetches secret data from a server-only module. This module should never be exposed to the browser for security reasons.
🎯 Goal: Create a server-only module that exports a secret message. Then, import and use this module in a server component to display the secret message safely.
📋 What You'll Learn
Create a server-only module file named secretMessage.ts exporting a constant string secret with value 'This is a secret from the server'.
Create a server component named SecretDisplay that imports secret from secretMessage.ts.
Render the secret message inside a <div> with an accessible aria-label describing it as 'Secret message'.
Ensure the server-only module is not imported in any client component.
💡 Why This Matters
🌍 Real World
Server-only modules are used to keep sensitive data or logic hidden from the browser, such as API keys, database queries, or secret messages.
💼 Career
Understanding server-only modules is important for building secure Next.js applications and working with server components effectively in professional web development.
Progress0 / 4 steps
1
Create the server-only module
Create a file named secretMessage.ts and export a constant called secret with the exact string value 'This is a secret from the server'.
NextJS
Need a hint?

Use export const secret = 'This is a secret from the server'; in secretMessage.ts.

2
Create the server component
Create a React server component named SecretDisplay in a file SecretDisplay.tsx. Import secret from ./secretMessage.
NextJS
Need a hint?

Define a function component that returns a <div> with aria-label="Secret message" and displays {secret}.

3
Use the server component in a page
In the app/page.tsx file, import the SecretDisplay component from ./SecretDisplay and render it inside the default exported function.
NextJS
Need a hint?

Render <SecretDisplay /> inside a <main> element in the page component.

4
Confirm server-only module usage
Ensure that secretMessage.ts is only imported in server components like SecretDisplay.tsx and not in any client components. Add a comment in secretMessage.ts stating it is server-only.
NextJS
Need a hint?

Add a comment // This module is server-only at the top of secretMessage.ts.