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';
import * as PrismaModule from '.prisma/client';
const context = getContext(config, PrismaModule);
// ... whatever you need

For inspiration, see the script example project, and how we use tsx to seed the database with some data.

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.