#Where to call FetchData method

1 messages · Page 1 of 1 (latest)

austere knoll
#

I'm currently working on Next14project.
And made FetchData method like this.
export async function fetchData({ method, url, data, cache }: FetchDataProps) {
const fullURL = process.env.BASE_API_URL + url;
let options: {
method: string;
mode: RequestMode;
credentials: RequestCredentials;
headers: {
"Content-Type": string;
Authorization?: string;
};
body?: any;
} = {
method,
mode: "cors",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
Authorization: Bearer ${localStorage.getItem("token")},
},
};
if (method === FetchMethods.POST) {
options = {
...options,
body: JSON.stringify(data),
};
}
try {
const response = await fetch(fullURL, options);
console.log(response);
} catch (err) {
console.log(err);
}
}

But I'm not sure in where I have to call this method.
I guess next 14 is a little different from Next 13.
But the GPT says I have to do it on getStaticProps or getServersideProps.
GPT is right or not? If not, please let me know the right way.

elfin ploverBOT
#

Hi @austere knoll. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, the GPT is correct. In Next.js, data fetching methods like the one you've created are typically called within special functions like getStaticProps or getServerSideProps. These functions run on the server-side and are used to fetch data that is needed to render your pages.

If you want to fetch data at build time and generate static pages, you can use getStaticProps. Here's an example from the Next.js documentation (https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props):

export async function getStaticProps() {
  const posts = await fetchData({ method: 'GET', url: '/posts', cache: 'no-store' });
  return {
    props: {
      posts,
    },
  };
}

On the other hand, if you need to fetch data on each request, you can use getServerSideProps. Here's an example from the Next.js documentation (https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props):

export async function getServerSideProps() {
  const data = await fetchData({ method: 'GET', url: '/data', cache: 'no-store' });
  return { props: { data } };
}

Remember, getStaticProps runs at build time on the server-side and is ideal for pages that can be pre-rendered ahead of a user's request. While getServerSideProps runs on each request and is ideal for pages that have data that changes frequently and needs to be updated on each request.

#

In Next.js 14, you can also use Server Components (https://nextjs.org/docs/app/building-your-application/rendering/server-components) to colocate your data fetching inside your React components. This allows you to send less JavaScript to the client, while maintaining the rendered HTML from the server. However, this approach is more advanced and may not be necessary for all use cases.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@austere knoll kapa.ai is still learning and improving, please let us know how it did by reacting below

austere knoll
#

Next14 Route.ts usage

#

@elfin plover Next14 Route.ts usage

elfin ploverBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js 14, the usage of route.ts is similar to Next.js 13. Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. They are defined in a route.js|ts file inside the app directory and can be nested inside the app directory, similar to page.js and layout.js. However, there cannot be a route.js file at the same route segment level as page.js.

Here's an example of a Route Handler:

// app/example/route.ts
export async function GET(request: Request) {}

The following HTTP methods are supported: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS. If an unsupported method is called, Next.js will return a 405 Method Not Allowed response.

You can also use Route Handlers to create custom request handlers for a given route. For example, you can create a handler for the GET method like this:

// app/example/route.ts
export async function GET(request: Request) {
  // Your custom logic here
}

A route.ts file can export an async function named by the HTTP verbs: GET, HEAD, OPTIONS, POST, PUT, DELETE, and PATCH. These functions can then be wrapped and abstracted to create helpers / reusable logic for your custom route logic.

// app/example/route.ts
import { cookies } from 'next/headers';
 
export async function GET(request: Request) {
 const cookieStore = cookies();
 const token = cookieStore.get('token');
 
 return new Response('Hello, Next.js!', {
 status: 200,
 headers: { 'Set-Cookie': `token=${token}` },
 });
}

Route Handlers will render a static response when running next build. Only the GET HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data.

#

@austere knoll kapa.ai is still learning and improving, please let us know how it did by reacting below

austere knoll
#

in where calls get Current User from Token in Next 14

#

@elfin plover in where calls get Current User from Token in Next 14

elfin ploverBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js, you can fetch the current user from a token typically in your getServerSideProps or getStaticProps functions, or within a custom API route. However, the exact location depends on your application's structure and needs.

If you're using a library like NextAuth.js, Clerk, Auth0, Stytch, or Kinde for authentication, they usually provide their own methods to get the current user. For example, with NextAuth.js, you can use the useSession hook on the client-side to get the current user.

If you're manually handling sessions or JWTs, you might have a function that decodes the JWT stored in localStorage or a cookie, and fetches the user data from your database or another API.

Here's an example of how you might do this in getServerSideProps, assuming you have a getUserFromToken function that takes a token and returns the corresponding user:

export async function getServerSideProps(context) {
  const token = context.req.cookies.token;
  const user = await getUserFromToken(token);

  if (!user) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    }
  }

  return {
    props: { user },
  }
}

In this example, getUserFromToken is a hypothetical function that you would need to implement yourself, based on how you're storing and validating your tokens.

Remember, storing JWTs in localStorage is not recommended due to potential XSS attacks. It's safer to store tokens in HttpOnly cookies, which are not accessible by JavaScript running in the browser.

#

@austere knoll kapa.ai is still learning and improving, please let us know how it did by reacting below