Uh-oh! There seems to be an issue with the response. It appears that the

Struggling to navigate the graphql in apollo client/server for a Next.js project. The terminal is showing an error message

No HTTP methods exported in '..\app\api\graphql\route.ts'. Export a named export for each HTTP method.
. I'm still new to these technologies and unsure about the directory structure. All four files mentioned are located in the same folder app/api/graphql.

Below are the code snippets:

ApolloClient.ts
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc";

export const { getClient } = registerApolloClient(() => {
    return new ApolloClient({
        cache: new InMemoryCache(),
        link: new HttpLink({
            uri: "http://localhost:3000/api/graphql",

        }),
    });
});
typeDefs.ts
import { ApolloServer } from "@apollo/server";
import { gql } from "graphql-tag";
        
const typeDefs = gql`
    type Query {
        hello: String
    }
`;

export default typeDefs;
resolver.ts
const resolvers = {
    Query: {
        hello: () => 'world',
    },
};

export default resolvers;
graphql.ts
import { ApolloServer } from "@apollo/server";
import typeDefs from './typeDefs';
import resolvers from './resolvers';
import { startServerAndCreateNextHandler } from "@as-integrations/next";

const graphql = new ApolloServer({
    resolvers,
    typeDefs
});

export default startServerAndCreateNextHandler(graphql);   

Error displayed on the browser:

    Unhandled Runtime Error
    Error: Response not successful: Received status code 405
    
    Call Stack
    - Traces of errors -

Answer №1

To define functions in the App Router, you must export them as HTTP method names. See the example below:

export const GET = (req: Request) => {
    return Response.json({ content: [] })
}

export const POST = (req: Request) => {
    return Response.json({ posted: true })
}

export const DELETE = (req: Request) => {
    return Response.json({ deleted: true })
}

export const PUT = (req: Request) => {
    return Response.json({ updated: true })
}

It appears that @as-integrations/next does not provide dedicated functions for this purpose, likely to maintain compatibility with the pages router. Instead, they suggest using the following approach:

graphql/route.ts
const handler = startServerAndCreateNextHandler(server);

export { handler as GET, handler as POST };

Answer №2

The issue was resolved by incorporating page.ts with the code snippet below:

const userQuery = gql`
  query {   
      hello    
  }
`;

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

Tips for enforcing strict typing in TypeScript when implementing abstract functions

Consider the following scenario with two classes: abstract class Configuration { abstract setName(name: string); } class MyConfiguration extends Configuration { setName(name) { // set name. } } In this setup, the name parameter in M ...

Exploring the capabilities of supertest by testing endpoints in Express with NodeJS

Having trouble setting up a test environment to test my TypeScript Express Node.js endpoints. Here are the packages I've installed: jest ts-jest jest-junit supertest @types/supertest @types/jest This is how my spec file looks like: imp ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

Retrieving routing information from directives within angular2

const APP_ROUTES: RouterConfig = [ { path: 'app/home', component: HomeComponent, data: { name: 'Home' } } ] Assuming the route configuration is set as displayed above, how can one ...

The error message "ng: command not found" popped up despite successfully installing the latest @angular/cli using npm linking

Here is the information about my current setup: Node version: v10.15.3 NPM version: 6.4.1 I attempted to run the following command: Command: npm i -g angular/cli An error occurred while executing: npm ERR! /usr/local/bin/git ls-remote -h -t ssh:// ...

What is the process for retrieving the API configuration for my admin website to incorporate into the Signin Page?

My admin website has a configuration set up that dynamically updates changes made, including the API. However, I want to avoid hardcoding the base URL for flexibility. How can I achieve this? Please see my admin page with the config settings: https://i.st ...

Comparing angular2/core and @angular/core: What sets them apart?

Maybe this is a silly question, but I've noticed that there are multiple instances of import {Component} from 'angular2/core' and import {Component} from '@angular/core' However, I can't seem to grasp when to use one ove ...

What is the best way to connect to a library using a script within a Typescript React application?

I'm a newbie to React and haven't worked on web development in years, so I'm facing a basic issue: Currently, I'm working on implementing a Stripe-based payment flow in a React web app (written in Typescript) and I've hit a roadbl ...

Enhancing Type Safety in Typescript through Key/Property Type Guards

Is it possible to create a typeguard that can confirm the existence (or specific type) of a property in an object? For example: Consider an interface Foo: interface Foo { bar: string; baz: number; buzz?: string; } An object of type Foo may ...

Tips for obtaining the iframe #document with cheeriojs?

I've been struggling to scrape the anime videos page [jkanime], specifically with extracting the mp4 video formats embedded in an iframe #document. Despite trying to use cheerio for querying, I've only managed to retrieve src links from Facebook ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

Typescript's implementation of AngularJs provider

After creating an Angularjs provider in typescript, I found myself wondering if there might be a more efficient way to achieve the same outcome. My current provider serves as an abstraction for a console logger, with the interface primarily designed to s ...

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

How can I store an array of objects in a Couchbase database for a specific item without compromising the existing data?

Here is an example: { id:1, name:john, role:[ {name:boss, type:xyz}, {name:waiter, type:abc} ] } I am looking to append an array of objects to the existing "role" field without losing any other data. The new data should be added as individual ob ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

Tips for implementing Peer.js in Next.js using TypeScript?

Next.js has the ability to run on the server side, which can result in Peer.js throwing errors when used with Next.js. One user on Stack Overflow explains this issue: The error is likely due to peer js performing side effects during import. The suggest ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

TypeScript does not raise errors for ANY variables that are initialized later

In my code, there is a function that accepts only numeric variables. function add(n1: number) { return n1 + n1; } However, I mistakenly initialized a variable with type "any" and assigned it a string value of '5'. let number1; number1 = &apo ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...