DEV Community

Cover image for How to add a Graphql endpoint into a Sveltekit app
vibhanshu pandey
vibhanshu pandey

Posted on • Edited on

4

How to add a Graphql endpoint into a Sveltekit app

Warning: The code provided in this post is not well tested for every environment, and may not provide all the features, use with caution.

Hello, In this post I will show you how you can add a graphql endpoint in a sveltekit app with apollo-server-lambda.

TLDR;

If you want to start quickly, here's the boilerplate Repo: https://github.com/vibhanshu909/sveltekit-with-graphql

Note: I'm using typescript here, if you don't use typescript, make the required changes.
This Project also uses tailwindcss, if you don't want to use tailwindcss, perform the following steps.

  • Delete postcss.config.cjs, tailwindcss.config.cjs & src/app.css files.
  • remove postcss: true option in preprocess function from svelte.config.js file.
  • remove import '../app.css'; statement from the script block in __layout.svelte file.

Follow the below steps.

Step 1: Install the required dependencies

npm i apollo-server-lambda graphql
Enter fullscreen mode Exit fullscreen mode

Step 2: create a file src/routes/graphql.ts with the following contents.

import type { EndpointOutput, RequestHandler } from '@sveltejs/kit';
import { ApolloServer, gql } from 'apollo-server-lambda';

const typeDefs = gql`
    type Query {
        hello: String
    }
    type Mutation {
        double(x: Int!): Int!
    }
`;

// Provide resolver functions for your schema fields
const resolvers = {
    Query: {
        hello: () => 'Hello world!'
    },
    Mutation: {
        double: (_, { x }) => x * 2
    }
};

const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    playground: true,
    introspection: true,
    tracing: true
});

const graphqlHandler = apolloServer.createHandler();

// This is where the magic happens.
const handler: RequestHandler = async (args) => {
    return await new Promise<EndpointOutput>((resolve, reject) => {
        graphqlHandler(
            {
                httpMethod: args.method,
                headers: args.headers,
                path: args.path,
                body: args.rawBody as string
            } as any,
            {} as any,
            (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve({
                        status: result.statusCode,
                        body: result.body,
                        headers: result.headers as any
                    });
                }
            }
        ) as any;
    });
};

export const head = handler;
export const get = handler;
export const post = handler;

Enter fullscreen mode Exit fullscreen mode

Step 3: Test the endpoint.

npm run dev
Enter fullscreen mode Exit fullscreen mode

Goto http://localhost:3000/graphql, you should see the graphql playground.

And that's it. :)

Comment down below, if you have any questions.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
jdgamble555 profile image
Jonathan Gamble • Edited

This does not work with SvelteKit.

I got mine to work with this:

const handler = async ({ request }) => {

  const r = await request.json();

  return {
    body: await server.executeOperation(r)
  };

}

export const head = handler;
export const get = handler;
export const post = handler;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vibhanshu909 profile image
vibhanshu pandey

Yes, Unfortunately this no longer works, there's been a number of updates in the sveltekit repo.

Thinking of Archiving this, until further updates.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay