<commit_before><!--[meta]
section: api
title: Keystone class
order: 1
[meta]-->

# Keystone class

## Usage

```javascript
const { Keystone } = require('@keystonejs/keystone');

const keystone = new Keystone({
  /*...config */
});
```

## Config

| Option           | Type       | Default                         | Description                                                                                                                                       |
| ---------------- | ---------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `adapter`        | `Object`   | Required                        | The database storage adapter. See the [Adapter framework](https://keystonejs.com/keystonejs/keystone/lib/adapters/) docs for more details.        |
| `adapters`       | `Object`   | `undefined`                     | A list of named database adapters. Use the format `{ name: adapterObject }`.                                                                      |
| `appVersion`     | `Object`   | See [`appVersion`](#appversion) | Configure the application version and where it is made available.                                                                                 |
| `cookie`         | `Object`   | See: [`cookie`](#cookie)        | Cookie object used to configure the [express-session middleware](https://github.com/expressjs/session#cookie).                                    |
| `cookieSecret`   | `String`   | Required in production          | The secret used to sign session ID cookies. Should be long and unguessable.                                                                       |
| `defaultAccess`  | `Object`   | `undefined`                     | Default list, field, and custom schema access. See the [Access control API](https://www.keystonejs.com/api/access-control) docs for more details. |
| `defaultAdapter` | `String`   | `undefined`                     | The name of the database adapter to use by default if multiple are provided.                                                                      |
| `onConnect`      | `Function` | `undefined`                     | Callback that executes once `keystone.connect()` complete. Takes no arguments.                                                                    |
| `queryLimits`    | `Object`   | `{}`                            | Configures global query limits                                                                                                                    |
| `sessionStore`   | `Object`   | `undefined`                     | A compatible Express session middleware.                                                                                                          |
| `schemaNames`    | `Array`    | `['public']`                    |                                                                                                                                                   |

### `appVersion`

Configure the application version, which can be surfaced via HTTP headers or GraphQL

The `version` can be any string value you choose to use for your system.
If `addVersionToHttpHeaders` is `true` then all requests will have the header `X-Keystone-App-Version` set.
The version can also be queried from the GraphQL API as `{ appVersion }`.
You can control whether this is exposed in your schema using `access`, which can be either a boolean, or an object with `schemaName` keys and boolean values.

```javascript
const keystone = new Keystone({
  appVersion: {
    version: '1.0.0',
    addVersionToHttpHeaders: true,
    access: true,
  },
});
```

#### Why don't we just use `access` to control the HTTP header?

> We want to attach the HTTP header at the very top of the middleware stack, so if something gets rejected we can at least be sure of the system version that did the rejecting. This happens well before we have worked out which schema the person is trying to access, and therefore our access control isn’t ready to be used. Also, the access control that we set up is all about controlling access to the GraphQL API, and HTTP headers are a Different Thing, so even if it was technically possible to use the same mechanism, it really makes sense to decouple those two things.

### `queryLimits`

Configures global query limits.

These should be used together with [list query limits](https://keystonejs.com/api/create-list#query-limits).

```javascript
const keystone = new Keystone({
  queryLimits: {
    maxTotalResults: 1000,
  },
});
```

- `maxTotalResults`: limit of the total results of all relationship subqueries

Note that `maxTotalResults` applies to the total results of all relationship queries separately, even if some are nested inside others.

### `cookie`

_**Default:**_ see Usage.

A description of the cookie properties is included in the [express-session documentation](https://github.com/expressjs/session#cookie).

#### `secure`

A secure cookie is only sent to the server with an encrypted request over the HTTPS protocol. If `secure` is set to true (as is the default with a **production** build) for a KeystoneJS project running on a non-HTTPS server (such as localhost), you will **not** be able to log in. In that case, be sure you set `secure` to false. This does not affect development builds since this value is already false.

You can read more about secure cookies on the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies).

#### Usage

```javascript
const keystone = new Keystone({
  /* ...config */
  cookie: {
    secure: process.env.NODE_ENV === 'production', // Default to true in production
    maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
    sameSite: false,
  },
});
```

### `cookieSecret`

The secret used to sign session ID cookies. In production mode (`process.env.NODE_ENV === 'production'`) this option is required. In development mode, if undefined, a random `cookieSecret` will be generated each time Keystone starts (this will cause sessions to be reset between restarts).

### `sessionStore`

Sets the Express server's [session middleware](https://github.com/expressjs/session). This should be configured before deploying your app.

This example uses the [`connect-mongo`](https://github.com/jdesboeufs/connect-mongo) middleware, but you can use [any of the stores that work with `express session`](https://github.com/expressjs/session#compatible-session-stores).

```javascript
const expressSession = require('express-session');
const MongoStore = require('connect-mongo')(expressSession);

const keystone = new Keystone({
  sessionStore: new MongoStore({ url: 'mongodb://localhost/my-app' }),
});
```

## Methods

| Method                | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `connect`             | Manually connect to Adapters.                                                |
| `createAuthStrategy`  | Creates a new authentication middleware instance.                            |
| `createItems`         | Add items to a `Keystone` list.                                              |
| `createList`          | Add a list to the `Keystone` schema.                                         |
| `disconnect`          | Disconnect from all adapters.                                                |
| `extendGraphQLSchema` | Extend keystones generated schema with custom types, queries, and mutations. |
| `prepare`             | Manually prepare `Keystone` middlewares.                                     |
| `createContext`       | Create a `context` object that can be used with `executeGraphQL()`.          |
| `executeGraphQL`      | Execute a server-side GraphQL operation within the given context.            |

<!--

## Super secret methods

Hello curious user. Here are some undocumented methods you _can_ use.
Please note: We use these internally but provide no support or assurance if used in your projects.

| Method                | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `dumpSchema`          | Dump schema to a string.                                                       |
| `getTypeDefs`         | Remove from user documentation?                                              |
| `getResolvers`        | Remove from user documentation?                                              |
| `registerSchema`      | Remove from user documentation?                                              |
| `createItem`          | Remove from user documentation?                                              |
| `getAdminMeta`        | Remove from user documentation?                                              |

-->

### `connect()`

Manually connect Keystone to the adapters. See [Custom Server](https://keystonejs.com/guides/custom-server).
<commit_msg>[RFC] New API doc formatting proposal (#2500)<commit_after><!--[meta]
section: api
title: Keystone class
order: 1
[meta]-->

# Keystone class

## Usage

```javascript
const { Keystone } = require('@keystonejs/keystone');

const keystone = new Keystone({
  adapter,
  adapters,
  appVersion,
  cookie,
  cookieSecret,
  defaultAccess,
  defaultAdapter,
  onConnect,
  queryLimits,
  sessionStore,
  schemaNames,
});
```

### `appVersion`

Configure the application version, which can be surfaced via HTTP headers or GraphQL.

The `version` can be any string value you choose to use for your system. If `addVersionToHttpHeaders` is `true` then all requests will have the header `X-Keystone-App-Version` set. The version can also be queried from the GraphQL API as `{ appVersion }`. You can control whether this is exposed in your schema using `access`, which can be either a boolean, or an object with `schemaName` keys and boolean values.

```javascript
const keystone = new Keystone({
  appVersion: {
    version: '1.0.0',
    addVersionToHttpHeaders: true,
    access: true,
  },
});
```

#### Why don't we just use `access` to control the HTTP header?

> We want to attach the HTTP header at the very top of the middleware stack, so if something gets rejected we can at least be sure of the system version that did the rejecting. This happens well before we have worked out which schema the person is trying to access, and therefore our access control isn’t ready to be used. Also, the access control that we set up is all about controlling access to the GraphQL API, and HTTP headers are a Different Thing, so even if it was technically possible to use the same mechanism, it really makes sense to decouple those two things.

### `cookie`

_**Default:**_ see Usage.

A description of the cookie properties is included in the [express-session documentation](https://github.com/expressjs/session#cookie).

#### `secure`

A secure cookie is only sent to the server with an encrypted request over the HTTPS protocol. If `secure` is set to true (as is the default with a **production** build) for a KeystoneJS project running on a non-HTTPS server (such as localhost), you will **not** be able to log in. In that case, be sure you set `secure` to false. This does not affect development builds since this value is already false.

You can read more about secure cookies on the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies).

#### Usage

```javascript
const keystone = new Keystone({
  /* ...config */
  cookie: {
    secure: process.env.NODE_ENV === 'production', // Default to true in production
    maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
    sameSite: false,
  },
});
```

### `cookieSecret`

The secret used to sign session ID cookies. In production mode (`process.env.NODE_ENV === 'production'`) this option is required. In development mode, if undefined, a random `cookieSecret` will be generated each time Keystone starts (this will cause sessions to be reset between restarts).

### `defaultAccess`

_**Default:**_

```js
{
  list: true,
  field: true,
  custom: true
}
```

Default list and field access. See the [Access Control](https://www.keystonejs.com/api/access-control#defaults) page for more details.

### `defaultAdapter`

_**Default:**_ `undefined`

The name of the database adapter to use by default if multiple are provided.

### `onConnect`

_**Default:**_ `undefined`

Callback function that executes once `keystone.connect()` is complete. Takes no arguments.

### `queryLimits`

Configures global query limits.

These should be used together with [list query limits](https://keystonejs.com/api/create-list#query-limits).

```javascript
const keystone = new Keystone({
  queryLimits: {
    maxTotalResults: 1000,
  },
});
```

- `maxTotalResults`: limit of the total results of all relationship subqueries

Note that `maxTotalResults` applies to the total results of all relationship queries separately, even if some are nested inside others.

### `sessionStore`

Sets the Express server's [session middleware](https://github.com/expressjs/session). This should be configured before deploying your app.

This example uses the [`connect-mongo`](https://github.com/jdesboeufs/connect-mongo) middleware, but you can use [any of the stores that work with `express session`](https://github.com/expressjs/session#compatible-session-stores).

```javascript
const expressSession = require('express-session');
const MongoStore = require('connect-mongo')(expressSession);

const keystone = new Keystone({
  sessionStore: new MongoStore({ url: 'mongodb://localhost/my-app' }),
});
```

### `schemaNames`

_**Default:**_ `['public']`

## Methods

| Method                | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `connect`             | Manually connect to Adapters.                                                |
| `createAuthStrategy`  | Creates a new authentication middleware instance.                            |
| `createItems`         | Add items to a `Keystone` list.                                              |
| `createList`          | Add a list to the `Keystone` schema.                                         |
| `disconnect`          | Disconnect from all adapters.                                                |
| `extendGraphQLSchema` | Extend keystones generated schema with custom types, queries, and mutations. |
| `prepare`             | Manually prepare `Keystone` middlewares.                                     |
| `createContext`       | Create a `context` object that can be used with `executeGraphQL()`.          |
| `executeGraphQL`      | Execute a server-side GraphQL operation within the given context.            |

<!--
## Super secret methods

Hello curious user. Here are some undocumented methods you _can_ use.
Please note: We use these internally but provide no support or assurance if used in your projects.

| Method                | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `dumpSchema`          | Dump schema to a string.                                                       |
| `getTypeDefs`         | Remove from user documentation?                                              |
| `getResolvers`        | Remove from user documentation?                                              |
| `registerSchema`      | Remove from user documentation?                                              |
| `createItem`          | Remove from user documentation?                                              |
| `getAdminMeta`        | Remove from user documentation?                                              |
-->

### `connect()`

Manually connect Keystone to the adapters. See [Custom Server](https://keystonejs.com/guides/custom-server).

{'fraction_non_alphanumeric': 0.1240582931950105, 'fraction_numerical': 0.0029640607632456465, 'mean_word_length': 1.8293151642208245, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 18, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 84, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7630422', 'n_tokens_mistral': 3797, 'n_tokens_neox': 3582, 'n_words': 1509}