### Install and Run Keystone Project
Source: https://github.com/keystonejs/keystone/blob/main/examples/byte-encoding/README.md
Instructions for cloning the Keystone repository, installing dependencies, and starting the development server for the byte encoding example project.
```shell
pnpm install
cd examples/byte-encoding
pnpm dev
```
--------------------------------
### Basic Authentication Setup
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/auth.md
Example of how to configure authentication with a User list, specifying identity and secret fields, and enabling initial item creation.
```APIDOC
## Basic Authentication Setup
### Description
This example demonstrates the basic setup for authentication in KeystoneJS using the `createAuth` function. It configures the system to use a 'User' list, with 'email' as the identity field and 'password' as the secret field. It also includes options for session data and initializing the first item in the database.
### Code
```typescript
import { config, list } from '@keystone-6/core'
import { text, password, checkbox } from '@keystone-6/core/fields'
import { createAuth } from '@keystone-6/auth'
const { withAuth } = createAuth({
// Required options
listKey: 'User',
identityField: 'email',
secretField: 'password',
// Additional options
sessionData: 'id name email',
initFirstItem: {
fields: ['email', 'password'],
itemData: { isAdmin: true },
skipKeystoneWelcome: false,
},
})
export default withAuth(
config({
lists: {
User: list({
fields: {
email: text({ isIndexed: 'unique' }),
password: password(),
isAdmin: checkbox(),
},
}),
session: { /* ... */ },
},
})
)
```
```
--------------------------------
### Initial User List Setup
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-2.md
This is the starting point from Lesson 1, defining a basic User list with name and email fields.
```typescript
import { config, list } from '@keystone-6/core';
import { allowAll } from '@keystone-6/core/access';
import { text } from '@keystone-6/core/fields';
export default config({
db: {
provider: 'sqlite',
url: 'file:./keystone.db',
},
lists: {
User: list({
access: allowAll,
fields: {
name: text({ validation: { isRequired: true } }),
email: text({ validation: { isRequired: true }, isIndexed: 'unique' }),
},
}),
},
});
```
--------------------------------
### Initial KeystoneJS Setup with User and Post Lists
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-3.md
This is the starting point of the KeystoneJS app, defining User and Post lists with basic fields and relationships. It sets up the database provider and configuration.
```typescript
import { list, config } from '@keystone-6/core';
import { text, relationship } from '@keystone-6/core/fields';
const lists = {
User: list({
fields: {
name: text({ validation: { isRequired: true } }),
email: text({ validation: { isRequired: true }, isIndexed: 'unique' }),
posts: relationship({ ref: 'Post.author', many: true }),
},
}),
Post: list({
fields: {
title: text(),
author: relationship({
ref: 'User.posts',
ui: {
displayMode: 'cards',
cardFields: ['name', 'email'],
inlineEdit: { fields: ['name', 'email'] },
linkToItem: true,
inlineCreate: { fields: ['name', 'email'] },
},
}),
},
}),
};
export default config({
db: {
provider: 'sqlite',
url: 'file:./keystone.db',
},
lists,
});
```
--------------------------------
### Install Dependencies
Source: https://github.com/keystonejs/keystone/blob/main/examples/document-field-customisation/README.md
Run this command to install all project dependencies. Ensure you are in the repository root.
```shell
pnpm
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/keystonejs/keystone/blob/main/examples/framework-nextjs-two-servers/README.md
Run this command at the root of the repository to install all necessary project dependencies.
```shell
pnpm install
```
--------------------------------
### Run Project Instructions
Source: https://github.com/keystonejs/keystone/blob/main/examples/custom-session-redis/README.md
Instructions for cloning the repository, installing dependencies, and running the development server.
```shell
pnpm install
pnpm dev
```
--------------------------------
### Start Keystone development server
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/getting-started.md
Navigate into your project directory and run this command to start the Keystone development server. This will launch the Admin UI.
```bash
cd my-app
npm run dev
```
--------------------------------
### Add Keystone Postinstall Script
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/blog/embedded-mode-with-sqlite-nextjs.md
Includes the `keystone postinstall` script in `package.json` to ensure proper setup after dependency installation.
```diff
"scripts": {
+ "postinstall": "keystone postinstall",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
```
--------------------------------
### Start Keystone in Development Mode
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Command to start Keystone for local development. It generates necessary files, applies database migrations, and starts the dev server.
```bash
$ keystone dev
```
--------------------------------
### Install Dependencies
Source: https://github.com/keystonejs/keystone/blob/main/examples/graphql-gql.tada/README.md
Install project dependencies using pnpm.
```shell
pnpm install
```
--------------------------------
### Start Keystone in Production
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Starts Keystone in production mode. Requires a prior build. Does not generate or apply database migrations by default.
```bash
keystone start
```
--------------------------------
### Run Project Instructions
Source: https://github.com/keystonejs/keystone/blob/main/examples/custom-id/README.md
Instructions for cloning the repository, installing dependencies, and running the development server for the custom ID project.
```shell
pnpm install
cd examples/custom-id
pnpm dev
```
--------------------------------
### Install GraphQL-Tools Schema
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/schema-extension.md
Install the necessary package for schema merging.
```bash
npm install @graphql-tools/schema
```
--------------------------------
### Basic Keystone Configuration File
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-1.md
Create a keystone.ts file with minimal configuration to start.
```typescript
// keystone.ts
export default {};
```
--------------------------------
### Production Start Script
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
The script to start Keystone in production mode after the build process.
```bash
npx keystone start
```
--------------------------------
### Start Keystone Project
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Command to start the Keystone project in production mode. It triggers Prisma migrations on startup when `--with-migrations` is used.
```bash
$ keystone start --with-migrations
```
--------------------------------
### Install Keystone Auth Package
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-4.md
Installs the necessary @keystone-6/auth package for adding authentication features to your Keystone app.
```bash
npm install @keystone-6/auth
```
--------------------------------
### Run Keystone Tests
Source: https://github.com/keystonejs/keystone/blob/main/examples/testing/README.md
This script executes the tests defined in example-test.ts using tsx. Ensure you have installed dependencies with 'pnpm install'.
```shell
pnpm test
```
--------------------------------
### Build Keystone Project
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Command to build the Keystone project. This is required before running `keystone start`.
```bash
$ keystone build
```
--------------------------------
### Start Keystone with Migrations
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/database-migration.md
Apply migrations automatically when starting your Keystone server in production. This command ensures your database schema is up-to-date before the server begins accepting requests.
```sh
keystone start --with-migrations
```
--------------------------------
### Setup Keystone with Auth and Basic Lists
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-5.md
This code sets up a basic KeystoneJS project with User and Post lists, including authentication and session management.
```typescript
import { list, config } from '@keystone-6/core';
import { password, text, timestamp, select, relationship } from '@keystone-6/core/fields';
import { withAuth, session } from './auth';
const lists = {
User: list({
fields: {
name: text({ validation: { isRequired: true } }),
email: text({ validation: { isRequired: true }, isIndexed: 'unique' }),
posts: relationship({ ref: 'Post.author', many: true }),
password: password({ validation: { isRequired: true } })
},
}),
Post: list({
fields: {
title: text(),
publishedAt: timestamp(),
status: select({
options: [
{ label: 'Published', value: 'published' },
{ label: 'Draft', value: 'draft' },
],
defaultValue: 'draft',
ui: { displayMode: 'segmented-control' },
}),
author: relationship({ ref: 'User.posts' }),
},
}),
};
export default config(
withAuth({
db: {
provider: 'sqlite',
url: 'file:./keystone.db',
},
lists,
session,
ui: {
isAccessAllowed: (context) => !!context.session?.data,
},
})
);
```
--------------------------------
### Run Keystone Development Server
Source: https://github.com/keystonejs/keystone/blob/main/examples/extend-express-app/README.md
Starts the Keystone Admin UI and development server. Use the `--seed-data` flag to populate the database with initial items.
```shell
pnpm dev
```
```shell
pnpm dev --seed-data
```
--------------------------------
### Generated GraphQL Schema Example
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/graphql/overview.md
Example of the GraphQL schema generated by Keystone based on a simple User list definition.
```APIDOC
## Generated GraphQL Schema
### Description
Keystone generates a GraphQL API based on your schema definitions. The names and types of queries, mutations, and types are derived from your list and field configurations.
### Example System Definition
```typescript
import { config, list } from '@keystone-6/core';
import { text } from '@keystone-6/core/fields';
export default config({
lists: {
User: list({
fields: {
name: text()
}
}),
},
/* ... */
});
```
### Generated GraphQL Schema
```graphql
type Query {
users(
where: UserWhereInput! = {}
orderBy: [UserOrderByInput!]! = []
take: Int
skip: Int! = 0
): [User!]
user(where: UserWhereUniqueInput!): User
usersCount(where: UserWhereInput! = {}): Int
}
type User {
id: ID!
name: String
}
input UserWhereUniqueInput {
id: ID
}
input UserWhereInput {
AND: [UserWhereInput!]
OR: [UserWhereInput!]
NOT: [UserWhereInput!]
id: IDFilter
name: StringNullableFilter
}
input IDFilter {
equals: ID
in: [ID!]
notIn: [ID!]
lt: ID
lte: ID
gt: ID
gte: ID
not: IDFilter
}
input StringNullableFilter {
equals: String
in: [String!]
notIn: [String!]
lt: String
lte: String
gt: String
gte: String
contains: String
startsWith: String
endsWith: String
mode: QueryMode
not: NestedStringNullableFilter
}
enum QueryMode {
default
insensitive
}
input NestedStringNullableFilter {
equals: String
in: [String!]
notIn: [String!]
lt: String
lte: String
gt: String
gte: String
contains: String
startsWith: String
endsWith: String
not: NestedStringNullableFilter
}
input UserOrderByInput {
id: OrderDirection
name: OrderDirection
}
enum OrderDirection {
asc
desc
}
type Mutation {
createUser(data: UserCreateInput!): User
createUsers(data: [UserCreateInput!]!): [User]
updateUser(where: UserWhereUniqueInput!, data: UserUpdateInput!): User
updateUsers(data: [UserUpdateArgs!]!): [User]
deleteUser(where: UserWhereUniqueInput!): User
deleteUsers(where: [UserWhereUniqueInput!]!): [User]
}
input UserUpdateInput {
name: String
}
input UserUpdateArgs {
where: UserWhereUniqueInput!
data: UserUpdateInput!
}
input UserCreateInput {
name: String
}
```
```
--------------------------------
### Create a new Keystone app
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/getting-started.md
Use this command to initiate a new Keystone project. It generates necessary files and installs dependencies.
```bash
npm create keystone-app@latest
cd my-app
npm run dev
```
--------------------------------
### Example Project Telemetry Report (JSON)
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/reference/telemetry.md
This is an example of the JSON structure for a project telemetry report, detailing package versions, database type, list counts, and field usage.
```json
{
"lastSentDate": "2025-07-28",
"packages": {
"@keystone-6/auth": "8.0.1",
"@keystone-6/core": "6.1.0",
"@keystone-6/document-renderer": "1.1.2",
"@keystone-6/fields-document": "5.0.2"
},
"database": "postgresql",
"lists": 3,
"fields": {
"unknown": 1,
"@keystone-6/text": 5,
"@keystone-6/timestamp": 2,
"@keystone-6/checkbox": 1
}
}
```
--------------------------------
### Install Keystone instance using npm
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/getting-started.md
Run this command in your desired project folder to create a new Keystone instance. It will generate a new folder with your project files.
```bash
npm create keystone-app@latest
```
--------------------------------
### Custom Navigation Component Example
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/custom-admin-ui-navigation.md
This example shows a complete custom navigation component that includes a dashboard link, all visible lists, and a link to the KeystoneJS documentation.
```tsx
import { NavigationContainer, NavItem, ListNavItems } from '@keystone-6/core/admin-ui/components'
import type { NavigationProps } from '@keystone-6/core/admin-ui/components'
export function CustomNavigation({ lists }: NavigationProps) {
return (
Dashboard
Keystone Docs
)
}
```
```ts
import { AdminConfig } from '@keystone-6/core/types'
import { CustomNavigation } from './components/CustomNavigation'
export const components: AdminConfig['components'] = {
Navigation: CustomNavigation
}
```
--------------------------------
### Start Keystone without Admin UI
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Starts Keystone in production mode without serving the Admin UI. Useful for production deployments where the UI is not needed.
```bash
keystone start --no-ui
```
--------------------------------
### Setup Keystone Test Environment
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/testing.md
Sets up the testing environment by importing necessary modules, configuring the database URL for parallel testing, and resetting the database before each test.
```typescript
import { getContext } from '@keystone-6/core/context';
import { resetDatabase } from '@keystone-6/core/testing';
import * as PrismaModule from '.prisma/client';
import baseConfig from './keystone';
const dbUrl = `file:./test-${process.env.JEST_WORKER_ID}.db`;
const prismaSchemaPath = path.join(__dirname, 'schema.prisma');
const config = { ...baseConfig, db: { ...baseConfig.db, url: dbUrl } };
beforeEach(async () => {
await resetDatabase(dbUrl, prismaSchemaPath);
});
const context = getContext(config, PrismaModule);
test('Your unit test', async () => {
// ...
});
```
--------------------------------
### Stateless vs Stored Sessions Configuration
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/session.md
Demonstrates the configuration setup for both stateless and stored sessions, highlighting the use of `statelessSessions` and `storedSessions`.
```typescript
import { config } from '@keystone-6/core';
import { statelessSessions, storedSessions } from '@keystone-6/core/session';
export default config({
// Stateless
session: statelessSessions({ /* ... */ }),
// Stored
session: storedSessions({ store: { /* ... */ }, /* ... */ }),
/* ... */
});
```
--------------------------------
### Install TypeScript Dependency
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-1.md
Add TypeScript as a development dependency if you are using TypeScript for configuration.
```bash
npm install typescript
```
--------------------------------
### Production Build Script
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
A typical production build script that installs dependencies, builds the Keystone project, and deploys database migrations.
```bash
npm i && npx keystone build && npx keystone prisma migrate deploy
```
--------------------------------
### Install Keystone Core Dependency
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/blog/embedded-mode-with-sqlite-nextjs.md
Add the core KeystoneJS package to your Next.js project to enable its features.
```bash
npm install @keystone-6/core
```
--------------------------------
### Configure Access Control for Lists and Fields
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/access-control.md
Example demonstrating how to configure access control at both the list and field levels within the Keystone configuration.
```typescript
import { config, list } from '@keystone-6/core';
import { text } from '@keystone-6/core/fields';
export default config({
lists: {
ListKey: list({
fields: {
fieldName: text({ access: { /* ... */ }, }),
},
access: { /* ... */ },
}),
},
});
```
--------------------------------
### Test Execution Output Summary
Source: https://github.com/keystonejs/keystone/blob/main/examples/testing/README.md
This is an example of the expected output after running the tests, indicating the number of tests passed and their duration.
```text
✔ Create a User using the Query API (139.404167ms)
✔ Check that trying to create user with no name (required field) fails (96.580875ms)
✔ Check access control by running updateTask as a specific user via context.withSession() (193.86275ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 0.072292
```
--------------------------------
### Configure Stateless Sessions
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/auth-and-access-control.md
Set up stateless sessions using `statelessSessions` for secure, cookie-based session management. Ensure you change the example secret.
```typescript
const session = statelessSessions({
secret: '-- EXAMPLE COOKIE SECRET; CHANGE ME --',
});
```
--------------------------------
### Configure Stateless Sessions
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/session.md
Example of configuring stateless sessions using `statelessSessions` with various options like secret, ironOptions, maxAge, secure, path, domain, and sameSite.
```typescript
import { config } from '@keystone-6/core';
import { statelessSessions } from '@keystone-6/core/session';
export default config({
session: statelessSessions({
secret: 'ABCDEFGH1234567887654321HGFEDCBA',
ironOptions: { /* ... */ },
maxAge: 60 * 60 * 24,
secure: true,
path: '/',
domain: 'localhost',
sameSite: 'lax',
}),
/* ... */
});
```
--------------------------------
### Style Custom Logo with @keystar/ui
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/custom-admin-ui-logo.md
For styling, it's recommended to use `@keystar/ui` components. This example shows how to apply basic styling to the custom logo component.
```tsx
import React from 'react';
import { Heading } from '@keystar/ui/typography';
function CustomLogo () {
return
Custom Logo here
}
export const components = {
Logo: CustomLogo
}
```
--------------------------------
### GraphQL Mutation for User Authentication
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/auth.md
Example of how to use the `authenticateUserWithPassword` mutation to log in a user and retrieve their session token and item data.
```graphql
mutation {
authenticateUserWithPassword(
email: "username@example.com",
password: "password"
) {
... on UserAuthenticationWithPasswordSuccess {
item {
id
email
}
}
... on UserAuthenticationWithPasswordFailure {
message
}
}
}
```
--------------------------------
### Run Without Express Server in Dev
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Use the `--no-server` flag with `keystone dev` to prevent the Express server from starting, while still watching for changes.
```bash
$ keystone dev --no-server
```
--------------------------------
### Custom Session Strategy with Time Validation
Source: https://github.com/keystonejs/keystone/blob/main/examples/custom-session-invalidation/README.md
Extends the default session strategy to add a 'startTime' to the session and customize the 'get' function. The 'get' function now checks if the user's password was changed after the session started, invalidating the session if so.
```typescript
import { statelessSessions } from '@keystone-6/core/session'
const maxSessionAge = 60 * 60 * 8 // 8 hours, in seconds
const withTimeData = (
_sessionStrategy: SessionStrategy>
): SessionStrategy> => {
const { get, start, ...sessionStrategy } = _sessionStrategy
return {
...sessionStrategy,
get: async ({ req, createContext }) => {
const session = await get({ req, createContext })
if (!session || !session.startTime) return
if (session.data.passwordChangedAt === null) return session
if (session.data.passwordChangedAt === undefined) {
throw new TypeError('passwordChangedAt is not listed in sessionData')
}
if (session.data.passwordChangedAt > session.startTime) {
return
}
return session
},
start: async ({ res, data, createContext }) => {
const withTimeData = {
...data,
startTime: new Date(),
}
return await start({ res, data: withTimeData, createContext })
},
}
}
const myAuth = (keystoneConfig: KeystoneConfig): KeystoneConfig => {
// Add the session strategy to the config
if (!keystoneConfig.session) throw new TypeError('Missing .session configuration')
return {
...keystoneConfig,
session: withTimeData(keystoneConfig.session),
}
}
```
--------------------------------
### Seed Sample Data Instructions
Source: https://github.com/keystonejs/keystone/blob/main/examples/custom-id/README.md
Steps to populate the database with sample content using the provided seed script.
```shell
pnpm seed-data
```
--------------------------------
### Document Field Configuration
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/fields/document.md
Configure the document field with various options like relationships, component blocks, formatting, links, dividers, and layouts. This example shows a basic setup within a Keystone list definition.
```typescript
import { config, list } from '@keystone-6/core';
import { document } from '@keystone-6/fields-document';
export default config({
lists: {
SomeListName: list({
fields: {
someFieldName: document({
relationships: { /* ... */ },
componentBlocks: {
block: { /* ... */ },
/* ... */
},
formatting: { /* ... */ },
links: true,
dividers: true,
layouts: [/* ... */],
}),
/* ... */
},
}),
/* ... */
},
/* ... */
});
```
--------------------------------
### Configure Initial User Creation
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/auth.md
Enable `initFirstItem` to allow bootstrapping the first user via the Admin UI. Configure fields, item data, and whether to skip the welcome screen.
```typescript
import { createAuth } from '@keystone-6/auth';
const { withAuth } = createAuth({
listKey: 'User',
identityField: 'email',
secretField: 'password',
initFirstItem: {
fields: ['email', 'password'],
itemData: { isAdmin: true },
skipKeystoneWelcome: false,
},
});
```
--------------------------------
### Initialize New Project Folder
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-1.md
Use these commands to create a new directory for your Keystone project and initialize it with npm.
```bash
mkdir keystone-learning
cd keystone-learning
npm init
```
--------------------------------
### Install Keystone instance using npx
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/getting-started.md
Alternatively, use npm's npx to create a new Keystone instance. This command also generates a new project folder with necessary files.
```bash
npx create-keystone-app@latest
```
--------------------------------
### Run Keystone Postinstall Script
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Command to run the postinstall script, which generates necessary files like Node.js API and TypeScript definitions. Recommended for ensuring files are up-to-date.
```bash
$ keystone postinstall
```
--------------------------------
### Run Keystone Dev Server
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-1.md
Execute this command in your project's root directory to start the Keystone development server. It will provide a link to the Admin UI upon successful startup.
```bash
npx keystone dev
```
--------------------------------
### Generated GraphQL Schema - Unique Input Example
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/graphql/overview.md
Illustrates an example of a 'UserWhereUniqueInput' type, which is generated when a field has 'isIndexed: "unique"' or a 1-to-1 relationship is defined. It shows multiple possible unique identifiers.
```graphql
input UserWhereUniqueInput {
id: ID
email: String
profile: ProfileWhereUniqueInput
}
```
--------------------------------
### Update Person by ID
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/auth-and-access-control.md
Example GraphQL mutation to update a person by their ID.
```graphql
mutation {
updatePerson(where: { id: 1 }) {
name
}
}
```
--------------------------------
### Query Person by ID
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/auth-and-access-control.md
Example GraphQL query to retrieve a person by their ID.
```graphql
query {
person(where: { id: 1 }) {
name
}
}
```
--------------------------------
### Initialize Authentication and Session Management
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-4.md
Set up createAuth with listKey, identityField, sessionData, secretField, and initFirstItem. Configure statelessSessions with maxAge and secret.
```typescript
import { createAuth } from '@keystone-6/auth';
import { statelessSessions } from '@keystone-6/core/session';
const { withAuth } = createAuth({
listKey: 'User',
identityField: 'email',
sessionData: 'name',
secretField: 'password',
initFirstItem: {
fields: ['name', 'email', 'password'],
},
});
let sessionSecret = '-- DEV COOKIE SECRET; CHANGE ME --';
let sessionMaxAge = 60 * 60 * 24; // 24 hours
const session = statelessSessions({
maxAge: sessionMaxAge,
secret: sessionSecret,
});
export { withAuth, session }
```
--------------------------------
### Define a Simple Virtual Field
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/virtual-fields.md
This example shows how to define a basic virtual field named 'hello' that always returns the string 'Hello, world!'. It requires importing `config`, `createSchema`, `g`, and `list` from `@keystone-6/core`, and `virtual` from `@keystone-6/core/fields`.
```typescript
import { config, createSchema, g, list } from '@keystone-6/core';
import { virtual } from '@keystone-6/core/fields';
export default config({
lists: {
Example: list({
fields: {
hello: virtual({
field: g.field({
type: g.String,
resolve() {
return "Hello, world!";
},
}),
}),
},
}),
},
});
```
--------------------------------
### GraphQL Query for Filtered Posts
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/auth-and-access-control.md
Example GraphQL query demonstrating how to filter posts by `isPublished` status.
```graphql
query {
posts(where: { isPublished: { equals: true } }) {
title
}
}
```
--------------------------------
### Query Posts by User (GraphQL)
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/relationships.md
Example GraphQL query to retrieve user names and the titles/content of posts they have authored.
```graphql
query {
users {
name
posts {
title
content
}
}
}
```
--------------------------------
### Query Authors of a Post (GraphQL)
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/relationships.md
Example GraphQL query to retrieve the title, content, and authors' names for posts.
```graphql
query {
posts {
title
content
authors {
name
}
}
}
```
--------------------------------
### Getting Image URL
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/context/overview.md
Generates the URL for an image given its mode, ID, and extension. This is part of the Images API.
```typescript
image.getUrl(mode, id, extension)
```
--------------------------------
### Keystone CLI Usage
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Basic usage of the Keystone CLI with available commands and options.
```text
$ keystone [command]
Commands
dev start the project in development mode (default)
postinstall build the project (for development, optional)
build build the project (required by `keystone start`)
start start the project
prisma run Prisma CLI commands safely
telemetry sets telemetry preference (enable/disable/status)
Options
--frozen (build)
don't build the graphql or prisma schemas, only validate them
--no-db-push (dev)
don't push any updates of your Prisma schema to your database
--no-prisma (build, dev)
don't build or validate the prisma schema
--no-server (dev)
don't start the express server
--no-ui (build, dev, start)
don't build and serve the AdminUI
--quiet (dev, build, start)
suppress most output except for errors
--with-migrations (start)
trigger prisma to run migrations as part of startup
```
--------------------------------
### Create Auth Configuration File
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-4.md
Creates a new auth.ts file to configure authentication settings, specifying the list, identity field, session data, and secret field.
```bash
touch auth.ts
```
--------------------------------
### Complete Keystone Configuration with New Fields
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/walkthroughs/lesson-3.md
This code demonstrates the full configuration of the User and Post lists, including the new `status` field with a default value and segmented control display. It also includes the database provider and list definitions.
```typescript
import { list, config } from '@keystone-6/core';
import { text, timestamp, select, relationship } from '@keystone-6/core/fields';
const lists = {
User: list({
fields: {
name: text({ validation: { isRequired: true } }),
email: text({ validation: { isRequired: true }, isIndexed: 'unique' }),
posts: relationship({ ref: 'Post.author', many: true }),
},
}),
Post: list({
fields: {
title: text(),
publishedAt: timestamp(),
status: select({
options: [
{ label: 'Published', value: 'published' },
{ label: 'Draft', value: 'draft' },
],
defaultValue: 'draft',
ui: { displayMode: 'segmented-control' },
}),
author: relationship({ ref: 'User.posts' }),
},
}),
};
export default config({
db: {
provider: 'sqlite',
url: 'file:./keystone.db',
},
lists,
});
```
--------------------------------
### GraphQL Query for Virtual Field Excerpt
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/virtual-fields.md
Example GraphQL query demonstrating how to request a virtual field with a specific argument value.
```graphql
{
posts {
id
excerpt(length: 100)
}
}
```
--------------------------------
### Keystone project file structure
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/getting-started.md
Overview of the files generated by `create-keystone-app`. Key files include `keystone.ts` for configuration and `schema.ts` for data modeling.
```bash
.\n├── auth.ts # Authentication configuration for Keystone\n├── keystone.ts # The main entry file for configuring Keystone\n├── node_modules # Your dependencies\n├── package.json # Your package.json with four scripts prepared for you\n├── package-lock.json # Your npm lock file\n├── README.md # Additional info to help you get started\n├── schema.graphql # GraphQL schema (automatically generated by Keystone)\n├── schema.prisma # Prisma configuration (automatically generated by Keystone)\n├── schema.ts # Where you design your data schema\n└── tsconfig.json # Your typescript config
```
--------------------------------
### Configuring an Integer Field
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/fields/integer.md
Example of configuring an integer field with a default value, database mapping, required validation, and unique indexing.
```typescript
import { config, list } from '@keystone-6/core';
import { integer } from '@keystone-6/core/fields';
export default config({
lists: {
SomeListName: list({
fields: {
someFieldName: integer({
defaultValue: 0,
db: { map: 'my_integer' },
validation: {
isRequired: true,
},
isIndexed: 'unique',
}),
/* ... */
},
}),
/* ... */
},
/* ... */
});
```
--------------------------------
### Init First Item Configuration
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/auth.md
Configure the initialization of the first user in the system. This option enables a form in the Admin UI to create an initial user if none exist.
```APIDOC
## initFirstItem
This option adds support for bootstrapping the first user into the system via the Admin UI.
If this option is enabled and there are no users in the system, the Admin UI will present a form to create an initial user in the system.
Once the user is created, they will be presented with a Keystone Welcome screen, and prompted to sign up to the Keystone mailing list to receive updates about the project.
#### Options {% #init-first-item-options %}
- `fields` (required): A list of fields to include in the initial user form.
- `itemData` (default: `{}`): An object containing extra data to add to the initial user.
- `skipKeystoneWelcome` (default: `false`): A flag to skip display of the Keystone Welcome screen.
```typescript
import { createAuth } from '@keystone-6/auth';
const { withAuth } = createAuth({
listKey: 'User',
identityField: 'email',
secretField: 'password',
initFirstItem: {
fields: ['email', 'password'],
itemData: { isAdmin: true },
skipKeystoneWelcome: false,
},
});
```
#### GraphQL API {% #init-first-item-graphql-api %}
Enabling `initFirstItem` will add the following elements to the GraphQL API.
```graphql
type Mutation {
createInitialUser(data: CreateInitialUserInput!): UserAuthenticationWithPasswordSuccess!
}
input CreateInitialUserInput {
name: String
email: String
password: String
}
```
##### createInitialUser
This mutation will create a new user in the system.
If a user already exists an error will be returned.
The available input fields are based on the `fields` options.
This mutation is used by the Admin UI's initial user screen and should generally not be called directly.
#### Admin UI {% #init-first-item-admin-ui %}
The initial user screen is added at `/init`, and users are redirected here if there is no active session and no users in the system.
```
--------------------------------
### Basic Keystone Configuration
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/config/config.md
The entry point for configuring a Keystone system is a default export of the `config` function in `keystone.ts`. This function accepts an object with various system configuration options.
```typescript
import { config } from '@keystone-6/core';
export default config({ /* ... */ });
```
--------------------------------
### Float Field Configuration
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/fields/float.md
Example of configuring a float field with a default value, database mapping, required validation, and unique indexing.
```typescript
import { config, list } from '@keystone-6/core';
import { float } from '@keystone-6/core/fields';
export default config({
lists: {
SomeListName: list({
fields: {
someFieldName: float({
defaultValue: 3.14159,
db: { map: 'my_float' },
validation: {
isRequired: true,
},
isIndexed: 'unique',
}),
/* ... */
},
}),
/* ... */
},
/* ... */
});
```
--------------------------------
### Create Next.js App with TypeScript
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/blog/embedded-mode-with-sqlite-nextjs.md
Use this command to create a new Next.js project with TypeScript support. Ensure you are in an empty directory.
```bash
npm create next-app --typescript my-project
cd my-project
```
--------------------------------
### Configure Calendar Day Field
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/fields/calendarday.md
Example of configuring a calendarDay field with various options including defaultValue, db.map, validation.isRequired, and isIndexed.
```typescript
import { config, list } from '@keystone-6/core';
import { calendarDay } from '@keystone-6/core/fields';
export default config({
lists: {
SomeListName: list({
fields: {
someFieldName: calendarDay({
defaultValue: '1970-01-01',
db: { map: 'my_date' },
validation: { isRequired: true },
isIndexed: 'unique',
}),
/* ... */
},
}),
/* ... */
},
/* ... */
});
```
--------------------------------
### BigInt Field Configuration
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/fields/bigint.md
Example of configuring a bigInt field with a default value, database mapping, required validation, and a unique index.
```typescript
import { config, list } from '@keystone-6/core';
import { bigInt } from '@keystone-6/core/fields';
export default config({
lists: {
SomeListName: list({
fields: {
someFieldName: bigInt({
defaultValue: 0n,
db: { map: 'my_bigint' },
validation: {
isRequired: true,
},
isIndexed: 'unique',
}),
/* ... */
},
}),
/* ... */
},
/* ... */
});
```
--------------------------------
### Build Keystone Project
Source: https://github.com/keystonejs/keystone/blob/main/docs/content/docs/guides/cli.md
Generates production-ready files for Keystone. Run this during your production deployment's build phase. It validates generated files against your Keystone Schema.
```bash
keystone build
```