Guide
Pothos builds a standard GraphQL schema from TypeScript. This guide creates a small schema, serves it with GraphQL Yoga, and runs a query against it.
Installing
Start in an empty directory with Node.js and npm installed:
npm init -y
npm pkg set type=moduleInstall Pothos, its graphql peer dependency, and Yoga:
npm install @pothos/core graphql graphql-yogaInstall TypeScript and tsx to check and run the example:
npm install --save-dev typescript @types/node tsxSet up TypeScript
Create tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"types": ["node"],
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["*.ts"]
}Pothos relies on strict null checking for its type inference. Keep strict enabled when adding
Pothos to an existing project too.
Create a simple schema
Create schema.ts:
import SchemaBuilder from '@pothos/core';
const builder = new SchemaBuilder({});
builder.queryType({
fields: (t) => ({
hello: t.string({
args: {
name: t.arg.string(),
},
resolve: (parent, { name }) => `hello, ${name ?? 'World'}`,
}),
}),
});
export const schema = builder.toSchema();queryType defines the fields clients can query. Here, hello returns a string and accepts an
optional name argument. Pothos infers the resolver's argument types from that definition.
toSchema() builds a graphql-js GraphQLSchema. You can use it with Yoga or another server that
accepts a GraphQLSchema.
Create a server
Create server.ts alongside schema.ts:
import { createServer } from 'node:http';
import { createYoga } from 'graphql-yoga';
import { schema } from './schema.js';
const yoga = createYoga({ schema });
const server = createServer(yoga);
server.listen(4000, () => {
console.log('Visit http://localhost:4000/graphql');
});Check the types, then start the server:
npx tsc
npx tsx server.tstsx runs TypeScript without checking types, so run tsc separately to catch type errors.
Run a query
Open http://localhost:4000/graphql to use Yoga's GraphiQL explorer. Run this query:
query {
hello(name: "Pothos")
}The response is:
{
"data": {
"hello": "hello, Pothos"
}
}Omit the name argument to get "hello, World". Stop the server with Ctrl+C when you're done.
Continue building
Objects shows how to expose your application's data. Fields covers resolvers, lists, and nullability, and Arguments explains how clients pass values to them. When your schema needs request data, see Context. App layout shows how to organize a larger schema across files.