Is it advisable to incorporate 'use server' into every function that retrieves confidential information within server components in Next.js?

By default, server components are enabled in Next.js 13. I'm contemplating whether I should wrap each fetch call in a separate function and include 'use server' to conceal the function's code or if it's acceptable to directly use fetch within the same function that returns the TSX?

Optional code wrapping with function and 'use server':

async function fetchData() {
  'use server'
  const response = await fetch('http://localhost:3001/test',{cache:'no-cache'})

  return response.json()
}

interface Test{
  age:number,
  name:string,
  likes:number,
}
 
export default async function Home() {

  const tests:Test[] = await fetchData()

  return (
    <div className='flex flex-row'>
      {tests.map((test)=>{
        return (
          <div>
            <div>
              {test.name}
            </div>
            <div>
              {test.age}
            </div>
            <div>
              Likes: {test.likes}
            </div>
          </div>
        )
      })}
    </div>
  )
}

Code without 'use server':

interface Test {
  age:number,
  name:string,
  likes:number,
}
 
export default async  function Home() {

  const response = await fetch('http://localhost:3001/test',{cache:'no-cache'})

  const tests:Test[] = await response.json()

  return (
    <div className='flex flex-row'>
      {tests.map((test)=>{
        return (
          <div>
            <div>
              {test.name}
            </div>
            <div>
              {test.age}
            </div>
            <div>
              Likes: {test.likes}
            </div>
          </div>
        )
      })}
    </div>
  )
}

Which of these versions offers more security, and when should each be utilized?

Answer №1

Within the app router in Next.js, Server Components are utilized by default, serving content from the server to the browser as HTML without any JavaScript code reaching the client side. This occurs until a "use client" is added at the top of a component.

The concept of "use server" is specifically designed for implementing features such as Server Actions through API routes in the app router. These actions involve functions marked with "use server" passed to form elements.

It's worth noting that although it may seem counterintuitive, "use server" should not be seen as the opposite of "use client". In fact, a component lacking "use client" is what contrasts with one that includes it, while "use server" serves a distinct purpose altogether.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

openssl reported an Error Stack error with code 03000086, specifically stating that there was an issue with the initialization

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_UNSUPPORTED' } Node.js v19.5.0 I e ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

Elevate the Appearance of Material UI Elements with custom CSS Sty

I am currently facing an issue while trying to customize the styling of a Material UI component using CSS. Here is the code snippet: <IconButton className="my-class"> <Close /> </IconButton> CSS: .my-class { float: right ...

Expanding Generic Interfaces in Typescript

I am working on a project where I need to enhance a typescript type by adding a new property in order to extend a generic type. To achieve this, I plan to define a Confidence<any> type that has the following structure: export interface Confidence< ...

Issue with TypeScript version 4.2.1 - The Array.some() method does not support a function that returns a boolean

I encountered a TypeScript error that goes as follows: https://i.sstatic.net/RoGER.png The complete error message reads: Supplied parameters do not match any signature of call target: parameter type mismatch. > Parameter 'Predicate' should ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

When the first argument is missing, using a recursive constraint default can result in the incorrect inference of the second argument, especially when both arguments share the same generic

Currently, I am developing a TypeScript implementation of a recursive binary search tree (BST) data structure using generic constraints. In order to establish a default for the recursive generic variable T without directly using it in the default declarati ...

Changing dot notation to bracket notation in Angular

Having trouble using dynamic columns in a Primeng table? The column fields need to be in bracket notation for this setup. What if you have a column with nested JSON structure and you're not sure how to write that in bracket notation? Don't worry, ...

The property y is not found on type x during property deconstruction

After creating a straightforward projectname.tsx file to contain my interfaces/types, I encountered an issue: export interface Movie { id: number; title: string; posterPath: string; } In another component, I aimed to utilize the Movie interface to s ...

Error message "Angular build with --prod causes Uncaught TypeError: e is not a constructor when running ng serve"

I am encountering an issue while deploying my Angular application to production. The application functions correctly in development and had previously worked on production as well. To build the application, I am using: ng build --prod --base-href="/site/ ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

OnDrop event in React is failing to trigger

In my current React + TypeScript project, I am encountering an issue with the onDrop event not working properly. Both onDragEnter and onDragOver functions are functioning as expected. Below is a snippet of the code that I am using: import * as React from ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

Struggling with the Transition from Google Sign-In

Having difficulty transitioning from Google Sign-In. "{error: 'idpiframe_initialization_failed', details: 'You have created a new client application that use…i/web/guides/gis-migration) for more information.'}" How do I u ...

Retrieving the property of a union type comprising a void type and an unnamed type

Currently, I am working on a project involving GraphQL. In my code, I have encountered a GraphQLError object with a property named extensions. The type of this property is either void or { [key: string]: any; }. Whenever I try to access any property within ...

Can dynamic values be sent to a custom form validator in Angular 6?

Essentially, I am facing a challenge with validating form inputs that are interdependent (for example, ensuring that the "from" time is earlier than the "to" time). However, I'm unsure of the best approach to tackle this issue. Below is my form group ...

Is it possible to enable password authentication on Firebase even if the user is currently using passwordless sign-on?

In my frontend JS project, I have integrated Firebase for web and am utilizing the passwordless (email link) authentication method for users. I am now interested in implementing password sign-on for an existing user who is currently using passwordless si ...