#Continuation of api

1 messages · Page 1 of 1 (latest)

marsh idol
#

kapa.ai
BOT
— Today at 12:52 PM
Let me check the knowledge base for you. One moment! 📚

The URL is visible because it's being logged to the console. If you don't want users to see the URL, you should remove or comment out any console.log statements that print the URL or the fetched data to the console.

However, if you're referring to the network requests being visible in the browser's developer tools, this is something that can't be avoided. When you make a fetch request in the browser, it's a network request that's visible in the developer tools network tab. This is a feature of the browser and there's no way to hide this from users who know how to use these tools.

If you want to completely hide the API endpoint from the client, you could create a server-side function (in Next.js, this would be an API Route) that makes the fetch request to the API endpoint. Your client-side code would then make a request to this server-side function, and all the client would see is the request to your server-side function, not the actual API endpoint.

Here's an example of how you can create a server-side function in Next.js:

// pages/api/tracking.js
export default async function handler(req, res) {
const no_resi = req.query.no_resi;
const response = await fetch(
<https://url.com/api/trackingpermember/${no_resi}/,>
{
headers: {
Authorization: Bearer ${process.env.ANTR_TOKEN},
},
}
);

const data = await response.json();

res.status(200).json(data);
}

Then, in your client-side code, you would fetch data from this server-side function instead of the actual API endpoint:

const res = await fetch(/api/tracking?no_resi=${trackingNumber});
const data = await res.json();
In this example, the client only sees a request to /api/tracking, and the actual API endpoint is hidden in the server-side function.

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

@raw mango

I am using the new app router
Do i need to name it page.tsx like other?
Can you help me structure and name it properly?

raw mangoBOT
#

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

#

Sure, I can help you with that. In the new App Router introduced in Next.js 13.2, you can create custom request handlers for a given route using the Web Request and Response APIs. These are called Route Handlers and they allow you to create a more modern version of API Routes that are deeply integrated into the new routing system for app.

Here's an example of how you can create a Route Handler:

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

export async function POST(request: Request) {
  // Your POST logic here
}

In this example, GET and POST are async functions named by the HTTP verbs. These functions can then be wrapped and abstracted to create helpers or reusable logic for your custom route logic.

You can also use other server functions, like cookies and headers, inside Route Handlers. Here's an example:

// 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}` },
 });
}

In this example, the GET function uses the cookies function from next/headers to get a cookie named token, and then returns a new Response with a 'Set-Cookie' header.

Remember, the file should be named as route.ts and placed inside the app directory or a subdirectory of app (e.g., app/api/[YOUR_API]/route.ts). The name of the file will determine the route where your API will be accessible.

#

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

marsh idol
#

can it be in:

src/app/folder1/components/foldername/route.ts ?

Or it should be one:

src/app/api/routename/route.ts ?

@raw mango

raw mangoBOT
#

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

#

The Route Handlers should be placed directly under the app directory or a subdirectory of app. The structure src/app/folder1/components/foldername/route.ts might not work as expected because the components directory is not typically used for routing.

The recommended structure for Route Handlers is src/app/api/routename/route.ts. This structure allows Next.js to correctly identify and handle the Route Handlers.

So, if you have a Route Handler for a route named routename, you should place the route.ts file in src/app/api/routename/.

Sources:


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

#

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

marsh idol
raw mangoBOT
#

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

#

Sure, I can help you with that. Here's how you can create a GET function in your Route Handler to fetch data from the specified URL with the provided token:

// src/app/api/trackingpermember/route.ts
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const response = await fetch('<https://url.com/api/trackingpermember/YNAD0396/',> {
    headers: {
      Authorization: `Bearer ASDF`,
    },
  });

  if (!response.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data');
  }

  const data = await response.json();

  return NextResponse.json(data);
}

In this example, the GET function fetches data from the specified URL with the provided token in the Authorization header. If the fetch request is successful, it returns the data as JSON using NextResponse.json(). If the fetch request fails, it throws an error.

Please replace '<https://url.com/api/trackingpermember/YNAD0396/'> and 'Bearer ASDF' with your actual URL and token.

Sources:


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

#

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

marsh idol
#

@raw mango

import { NextResponse } from "next/server";

export async function GET(request: Request) {
const response = await fetch(
${process.env.ANTR_URL}/api/trackingpermember/${value}/,
{
headers: {
Authorization: Bearer ${process.env.ANTR_TOKEN}},
},
}
);

if (!response.ok) {
// This will activate the closest error.js Error Boundary
throw new Error("Failed to fetch data");
}

const data = await response.json();

return NextResponse.json(data);
}

I want to pass value when request is made.
How do i do that

raw mangoBOT
#

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

#

To pass a value when a request is made, you can use dynamic route segments in your Route Handler. Dynamic segments are denoted by wrapping the segment name with square brackets ([]).

Here's how you can modify your Route Handler to accept a dynamic value:

// src/app/api/trackingpermember/[value]/route.ts
import { NextResponse } from "next/server";

export async function GET(request: Request, { params }: { params: { value: string } }) {
  const { value } = params;
  const response = await fetch(
    `${process.env.ANTR_URL}/api/trackingpermember/${value}/`,
    {
      headers: {
        Authorization: `Bearer ${process.env.ANTR_TOKEN}`,
      },
    }
  );

  if (!response.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error("Failed to fetch data");
  }

  const data = await response.json();

  return NextResponse.json(data);
}

In this example, the GET function accepts a second argument, params, which is an object that contains the dynamic segments of the route. The value is extracted from params and used in the fetch request.

Now, you can make a request to /api/trackingpermember/YNAD0396/, and YNAD0396 will be passed as the value.

Sources:


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

#

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

marsh idol
#

I want to get the data from body instead of the param

#

I want to get the data from body instead of the param

@raw mango

raw mangoBOT
#

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

#

Sure, if you want to get data from the body of a POST request instead of the URL parameters, you can use the request.json() or request.formData() methods to parse the body of the request.

Here's an example of how you can modify your Route Handler to get data from the body of a POST request:

// src/app/api/trackingpermember/route.ts
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  const { value } = await request.json();
  const response = await fetch(
    `${process.env.ANTR_URL}/api/trackingpermember/${value}/`,
    {
      headers: {
        Authorization: `Bearer ${process.env.ANTR_TOKEN}`,
      },
    }
  );

  if (!response.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error("Failed to fetch data");
  }

  const data = await response.json();

  return NextResponse.json(data);
}

In this example, the POST function uses the request.json() method to parse the body of the request and get the value. This value is then used in the fetch request.

Please replace '<https://url.com/api/trackingpermember/${value}/'> and 'Bearer ASDF' with your actual URL and token.

Sources:


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

#

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

marsh idol
#

@raw mango

http://localhost:3000/api/get-tracking/YNAD0396/

Is giving me page not found

Code:
import { NextResponse } from "next/server";

export async function GET(
request: Request,
{ params }: { params: { trackingNumber: string } }
) {
const { trackingNumber } = params;

const response = await fetch(
${process.env.ANTR_URL}/api/trackingpermember/${trackingNumber}/IC-MK-0089141086,
{
headers: {
Authorization: Bearer ${process.env.ANTR_TOKEN}},
},
}
);

if (!response.ok) {
// This will activate the closest error.js Error Boundary
throw new Error("Failed to fetch data");
}

const data = await response.json();

return NextResponse.json(data);
}

raw mangoBOT
#

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