This package provides an integration for using Apollo Server with SvelteKit. It allows you to easily set up a GraphQL server within your SvelteKit application.
To install the package, run the following command:
npm install apollo-server-integration-svelte
-
Create a new file named
+server.ts
inside thesrc/routes/api/graphql
directory of your SvelteKit project. -
Import the necessary modules and define your GraphQL schema and resolvers:
import { ApolloServer } from '@apollo/server';
import { startServerAndCreateSvelteKitHandler } from 'apollo-server-integration-svelte';
import type { RequestHandler } from 'apollo-server-integration-svelte';
import { gql } from 'graphql-tag';
const resolvers = {
Query: {
hello: () => 'world',
},
};
const typeDefs = gql`
type Query {
hello: String
}
`;
const server = new ApolloServer({
resolvers,
typeDefs,
});
export const GET: RequestHandler = startServerAndCreateSvelteKitHandler(server);
export const POST: RequestHandler = startServerAndCreateSvelteKitHandler(server);
You may also pass a context function to startServerAndCreateSvelteKitHandler
as such:
export const GET: RequestHandler = startServerAndCreateSvelteKitHandler(server, {
context: async (event) => ({ event, user: await getLoggedInUser(event) }),
});
export const POST: RequestHandler = startServerAndCreateSvelteKitHandler(server, {
context: async (event) => ({ event, user: await getLoggedInUser(event) }),
});
The SvelteKit RequestEvent
object is passed along to the context function.
When using this integration with SvelteKit, you can specify the type of the context object using the generic type parameter:
import type { RequestEvent } from '@sveltejs/kit';
// The context object will have the type { event: RequestEvent, user: User }
const handler = startServerAndCreateSvelteKitHandler<{ event: RequestEvent; user: User }>(server, {
context: async (event) => ({ event, user: await getLoggedInUser(event) }),
});
This ensures that the context object has the correct type signature.
This function takes an instance of ApolloServer
and optional options
and returns a request handler that can be used as a SvelteKit server route handler.
server
: An instance ofApolloServer
configured with your GraphQL schema and resolvers.options
(optional): An object containing additional options for the handler.context
(optional): A function that returns a custom context object for each request.
Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository.
This package is licensed under the MIT License.
This package is inspired by the official apollo-server-integration-next package and adapted for SvelteKit.
Special thanks to the Apollo Server and SvelteKit communities for their excellent work.