Error: The route in "src/app/api/orders/route.ts" does not conform to the necessary types for a Next.js Route. The "default" export field is not recognized as a valid Route

I need to retrieve the orders from the database using Prisma based on the user's email (authenticated via Google Provider). Here is the repository - https://github.com/Jayesh-kahnani/Snatch

Here is the API.

// src/app/api/order/route.ts
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../../lib/prisma";
import { getSession } from "next-auth/react";

export default async function (req: NextApiRequest, res: NextApiResponse) {
  try {
    const session = await getSession({ req });

    if (!session) {
      return res.status(401).json({ error: "Unauthorized" });
    }

    if (req.method !== "GET") {
      return res.status(405).json({ error: "Method Not Allowed" });
    }

    const userId = session.user?.email;

    if (!userId) {
      return res.status(400).json({ error: "User ID not found in session" });
    }

    const orders = await prisma.post.findMany({
      where: {
        author: { email: userId },
        published: true,
      },
      include: {
        author: { select: { name: true } },
      },
    });

    res.status(200).json({ orders });
  } catch (error) {
    console.error("Error fetching orders:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
}

This is the Page Component:

// src/app/user-orders/page.tsx
"use client"
import { useState, useEffect } from "react";
import Post from "../ui/order-list";

interface Order {
  id: string;
  title: string;
  content: string;
  authorName: string;
}

export default function Page() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchOrders() {
      try {
        const response = await fetch("/api/order/route");
        if (!response.ok) {
          throw new Error("Failed to fetch orders");
        }
        const data = await response.json();
        setOrders(data.orders);
        setLoading(false);
      } catch (error) {
        console.error("Error fetching orders:", error);
        setError("Failed to fetch orders. Please try again later.");
        setLoading(false);
      }
    }

    fetchOrders();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div className="container mx-auto mt-8 px-4 sm:px-0 text-gray-600">
      <h1 className="text-2xl font-bold text-gray-900 mb-4">Your Orders</h1>
      {orders.length === 0 ? (
        <div>No orders found.</div>
      ) : (
        <div className="flex flex-wrap">
          {orders.map((order) => (
            <Post
              key={order.id}
              title={order.title}
              content={order.content}
              authorName={order.authorName || "Unknown"}
            />
          ))}
        </div>
      )}
    </div>
  );
}

However, I am facing an error during deployment:

   ▲ Next.js 14.0.4
   - Environments: .env
   Creating an optimized production build ...
 ✓ Compiled successfully
   Linting and checking validity of types ...
Failed to compile.
src/app/api/orders/route.ts
Type error: Route "src/app/api/orders/route.ts" does not match the required types of a Next.js Route.
  "default" is not a valid Route export field.
Error: Command "npx prisma generate && next build" exited with 1

or refer to this image https://github.com/vercel/next.js/assets/120279764/e6112b7f-a9d1-410e-b8f1-ac7ceced4695

this is my src/app/api/auth/[...nextauth]/route.ts

import { PrismaClient } from "@prisma/client";
import NextAuth, { User as NextAuthUser } from "next-auth";
import GoogleProvider from "next-auth/providers/google";

interface MyUser extends NextAuthUser {
  email: string;
  name?: string;
}

const prisma = new PrismaClient();

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
  
  callbacks: {
    async signIn(params) {
      const { user } = params as { user: MyUser };

      try {
        const existingUser = await prisma.user.findUnique({
          where: { email: user.email },
        });

        if (!existingUser) {
          await prisma.user.create({
            data: {
              email: user.email,
              name: user.name || "",
            },
          });
        }

        return true;
      } catch (error) {
        console.error("Error during sign-in:", error);
        return false;
      }
    },
  },
});

export { handler as GET, handler as POST };

Please assist. I am struggling to understand the issue and how to resolve it. I am new to Next.js and TypeScript.

I was expecting to display the list of orders placed by the logged-in user.

Answer №1

It seems like there may be a syntax error:

export default async function (req: NextApiRequest, res: NextApiResponse) {}

You could consider using this alternative syntax:

export const FETCH = (req: NextRequest, res: NextResponse) => {};

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

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

Angular - The filter method cannot be used on Observables

I have a database with users who need to complete unique homework sessions. Each homework session has its own identifier, name, date, and other details. After fetching all the user's homework from the database, it is stored in a private variable call ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Is it feasible to utilize .NET Core as the Backend in place of Nextjs Api Routes without encountering any issues?

Currently working on an E-Commerce Website using NextJs. I'm aware that NextJS can handle both the front-end and back-end of the application. However, I'm curious about potential issues with SEO or other related factors if I were to switch from N ...

Encountering a module resolve error when a tsx file is added to the project item group

After setting up an asp.net core project with a react template and configuring Typescript, I created a simple file named Test.tsx with the following code: import React from 'react'; class Test extends React.Component { render() { r ...

Guide to populating a dropdown list using an array in TypeScript

I'm working on a project where I have a dropdown menu in my HTML file and an array of objects in my TypeScript file that I am fetching from an API. What is the best approach for populating the dropdown with the data from the array? ...

When elements are passed through components in Next.js, their style does not get applied

I have a unique component for the hero section of every page with varying content and heights. export default function CustomHero({ height, children, }: { height: string; children: ReactNode; }) { return ( <div className={`flex flex- ...

Error: Unable to locate the type definition file for the '@babel' package

I am currently working on a new project and here is the content of my package.json file. { "name": "dapp-boilerplate", "version": "1.0.0", "main": "index.js", "license": "MI ...

Encountering an error when implementing a router object within a TypeScript class in a Node.js environment

I have a Node.js service written in TypeScript. I am currently working on implementing a separate routing layer within the application. In my app.js file, I have the following code: let IndividualRoute= require('./routing/IndividualRoute'); app ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

Utilize the useState() hook to add an object and display its data in a React Native

Here is a function I am working with: const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}}); This is where I set the location: Geolocation.getCurrentPosition( location => { const date = d ...

Troubleshooting error "is not assignable to type..." when simulating global fetch using TypeScript

I am encountering an issue with the "global.fetch" part and cannot seem to figure out why. Despite following the standard procedure, I am still facing this TS2322 error. I am seeking assistance to understand why this error is occurring. I am open to sugges ...

Tailored component properties for React applications

I am currently working on configuring discriminative component props. Check out my code snippet below: import React, { ReactNode } from 'react' type SelectionModalProps<T> = ( | { multiSelect: true onSubmit: (data: T[]) => ...

Having trouble sending emails using Sendgrid on Next.js form

I am currently developing a request quote form in Next.js and utilizing SendGrid as a third-party API for handling email submissions. However, I have encountered an error that is preventing me from successfully linking the form to the email service. ...

Element is missing the necessary "key" property. (React and TypeScript)

Upon running the following code for reactJS and typescript, I encountered the error below: I have also included the import statement import 'bootstrap/dist/css/bootstrap.min.css'; in Index.tsx. Is there a solution to resolve this issue? npm s ...

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

Error 2322: Troubleshooting Typescript arrow functions overloads issues

Everything seems to be working well with the code below, except for an error that occurs with the resolve constant. const resolve: Resolve Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | ...

What is the reason for restricting a placeholder for an optional property in the interface to only be of type any?

I am facing a challenge with a file containing a single declaration, which is for an interface: interface NamedPerson { firstName: string; age?: number; [propName: string]: any; greet(lastName: string): void; } Everything works perfectly ...

What is the best way to encapsulate a slider within a fragment to prevent the occurrence of the "Type 'Element[]' is not assignable to type 'ReactNode'" error?

I'm encountering an issue with a Slider component in a NextJs landing page template. Every time I try to map through an array within the Slider component, I receive an error. I've attempted to find solutions online and came across this related th ...