#fetch /api/auth

1 messages · Page 1 of 1 (latest)

gaunt flareBOT
#

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

#

Sorry @orchid birch, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

orchid birch
#

@gaunt flare when i try to fetch /api/auth, i get

  • error TypeError: Failed to parse URL from /api/auth
    at authenticate (./app/login/auth.ts:18:24)
gaunt flareBOT
#

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

#

@orchid birch kapa.ai is still learning and improving, please let us how it did by reacting below

orchid birch
#

@gaunt flare how do i use useRouter with a server component

gaunt flareBOT
#

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

#

You cannot use useRouter with a server component. The useRouter hook and other hooks like usePathname and useSearchParams are only supported in Client Components. They cannot be used in Server Components. You can find more information about this in the App Router Incremental Adoption Guide (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration).

For server components, you can handle routing and data fetching using API Routes (https://nextjs.org/docs/api-routes/introduction) and Middleware (https://nextjs.org/docs/app/building-your-application/routing/middleware).

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

#

@orchid birch kapa.ai is still learning and improving, please let us how it did by reacting below

orchid birch
#

@gaunt flare i want the site to check if a user has a session token cookie, if they dont have it, when they visit /dashboard i want them to route it to /login and same for /login to /dashboard

gaunt flareBOT
#

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

#

You can achieve this by using Middleware (https://nextjs.org/docs/app/building-your-application/routing/middleware) to check for the session token cookie and rewrite the URL based on the user's authentication status. Here's an example of how you can implement this:

Create a middleware file, for example, middleware.ts:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const hasAuthToken = request.cookies.authToken;

  if (request.nextUrl.pathname === '/dashboard') {
    if (!hasAuthToken) {
      return NextResponse.rewrite(new URL('/login', request.url));
    }
  }

  if (request.nextUrl.pathname === '/login') {
    if (hasAuthToken) {
      return NextResponse.rewrite(new URL('/dashboard', request.url));
    }
  }
}

In this example, the middleware checks if the user has an authToken cookie. If the user tries to access /dashboard without an authToken, they will be redirected to /login. If the user tries to access /login with an authToken, they will be redirected to /dashboard.

Remember to add the middleware to your _middleware.ts file in the root of your project:

import { middleware as customMiddleware } from './middleware';

export default customMiddleware;

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

#

@orchid birch kapa.ai is still learning and improving, please let us how it did by reacting below

orchid birch
#

@gaunt flare i get an error when i upload this route to vercel ```tsx
import Link from "next/link";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";

type NewsData = {
sNo: number;
ID: number;
headline: string;
startDate: string;
endDate: string;
};

async function GetData() {
const server = process.env.SERVER;
const port = process.env.PORT;
const version = process.env.VERSION;

const res = await fetch(
http://${server}:${port}/api/v${version}/quickdrop/news,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
);
const datum = await res.json();
return datum; // remove the first two items
}
export default async function NewsPage() {
const data = await GetData();
return (
<>
<div className="flex flex-col w-full md:p-10 rounded-xl shadow-xl">
{data.map((article: NewsData) => (
<div key={article.sNo} className="flex flex-col items-center">
...
</div>
))}
</div>
</>
);
}

gaunt flareBOT
#

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

#

It seems like you're using an async function for your page component, which is not supported by default in Next.js. Instead, you should use getServerSideProps or getStaticProps to fetch data at request time or build time, respectively.

Here's an example of how you can modify your code using getServerSideProps:

import Link from "next/link";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";

type NewsData = {
  sNo: number;
  ID: number;
  headline: string;
  startDate: string;
  endDate: string;
};

async function GetData() {
  const server = process.env.SERVER;
  const port = process.env.PORT;
  const version = process.env.VERSION;

  const res = await fetch(
    `<http://${server}:${port}/api/v${version}/quickdrop/news`,>
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
  const datum = await res.json();
  return datum;
}

export async function getServerSideProps() {
  const data = await GetData();
  return { props: { data } };
}

export default function NewsPage({ data }: { data: NewsData[] }) {
  return (
    <>
      <div className="flex flex-col w-full md:p-10 rounded-xl shadow-xl">
        {data.map((article: NewsData) => (
          <div key={article.sNo} className="flex flex-col items-center">
              ...
          </div>
        ))}
      </div>
    </>
  );
}

In this example, I moved the data fetching logic to getServerSideProps, which will fetch the data on every request. The fetched data is then passed as a prop to the NewsPage component.

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

#

@orchid birch kapa.ai is still learning and improving, please let us how it did by reacting below

orchid birch
#

@gaunt flare i get a prerender error when pushing to vercel

gaunt flareBOT
#

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

#

It seems like you're encountering a prerender error when deploying your application to Vercel. One possible reason for this error is the FALLBACK_BODY_TOO_LARGE error, which occurs when the response buffer size exceeds the maximum value of 10 MB while fetching the content of a page (source (https://vercel.com/docs/errors/application-error-codes)).

To troubleshoot this issue, you can:

  1. Inspect the code for the page in question to see how you can reduce the amount and size of content being returned as HTML or JSON. This error can happen when the content is not available in the edge cache and needs to be fetched from the static file at origin. In that case, the prerender of a static file content has a limit of 10 MB.

  2. If the link is correct and you were not expecting this error, you can Contact Support (https://vercel.com/support).

If this doesn't resolve your issue, please provide more information about the specific error you're encountering, so I can better assist you.

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