Skip to Page NavigationSkip to Page NavigationSkip to Content

Get Context

Keystone's command line interface is helpful, but sometimes you don't want to startup the HTTP server, or kickoff any build processes. Maybe you need to insert data into the database, maybe you want to use Keystone with a custom protocol or a tiny REST API. Or maybe you want to write unit tests.

If you have previously run keystone build or keystone dev, then you can use getContext. If you change your configuration, you should rebuild your project before using getContext.

Using the getContext function does not use the typical Keystone entry point - it is a function and only requires that your Prisma client has been built and can be provided as a parameter with your Keystone configuration.

import { getContext } from '@keystone-6/core/context'
import config from './keystone.ts'
import * as PrismaModule from './generated/prisma/client.ts'
const context = getContext(config, PrismaModule)
// ... whatever you need

For inspiration, see the script example project, which uses Node.js's built-in TypeScript support to seed the database with some data. Running the example requires Node.js 22.18 or newer and "allowImportingTsExtensions": true in your `tsconfig.json. You can also use tools like tsx if you don't want to use imports with extensions that Node's built-in TypeScript support requires or you want to use syntax that Node's built-in TypeScript support doesn't support.

A context created in this way does not have an implicit session, nor is it a sudo() context. For more information about how to use a context, please see the overview.

The context returned from getContext is not a global - every time you instantiate it, you are instantiating a Prisma Client. Without careful usage, you may encounter the warnings that there are too many instances of your Prisma Client.