Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Ease setup of local Admin CLI with `create-spree-app` (#14174)

Damian Legawiecb39bce37e49a
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml
index 4466ade9e4..994e0415b7 100644
--- a/.github/workflows/packages.yml
+++ b/.github/workflows/packages.yml
@@ -342,9 +342,13 @@ jobs:
run: pnpm turbo build --filter=@spree/cli
working-directory: .
+ # Use `pnpm publish`, not `npm publish`: the CLI keeps @spree/admin-sdk as a
+ # `workspace:` devDependency, which `npm publish` would ship to the registry
+ # verbatim (EUNSUPPORTEDPROTOCOL on install). `pnpm publish` rewrites the
+ # `workspace:` protocol to the resolved semver range while packing.
- name: Publish
if: steps.check.outputs.published == 'false'
- run: npm publish --provenance --access public --tag ${{ steps.tag.outputs.tag }}
+ run: pnpm publish --provenance --access public --tag ${{ steps.tag.outputs.tag }} --no-git-checks
release-create-spree-app:
name: "create-spree-app - Release"
diff --git a/docs/developer/getting-started/quickstart.mdx b/docs/developer/getting-started/quickstart.mdx
index 783b98c816..874cf09873 100644
--- a/docs/developer/getting-started/quickstart.mdx
+++ b/docs/developer/getting-started/quickstart.mdx
@@ -77,6 +77,26 @@ Upon successful authentication, you should see the admin screen:
<img src="/images/spree_admin_dashboard.png" />
</Frame>
+## Using the Spree CLI
+
+Projects scaffolded with `create-spree-app` include [`@spree/cli`](/developer/cli/quickstart) for managing the backend and calling the Admin API. Because it's a project dependency, run it with `npx` (or any package-manager script):
+
+```bash
+npx spree dev # boot the Docker stack
+npx spree api get products # query the Admin API (read-only key preconfigured)
+```
+
+Project setup mints a read-only Admin API key into `.spree/credentials.json` (and `spree api` mints it on first use if you skipped setup), so `spree api` works without any extra configuration.
+
+To call `spree` directly without the `npx` prefix, install the CLI globally:
+
+```bash
+npm install -g @spree/cli
+spree api get products
+```
+
+See the [Spree CLI guide](/developer/cli/quickstart) for all commands and the [Admin API from the CLI](/developer/cli/admin-api) for querying your store's data.
+
## Next Steps
<CardGroup cols={2}>
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index af5e6bc270..eb00cf184c 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,11 @@
# @spree/cli
+## 2.3.0
+
+### Minor Changes
+
+- `spree init` now mints a read-only secret key and saves it to `.spree/credentials.json`, so `spree api` works immediately without a first-use minting round-trip. The setup summary shows both the Store API publishable key and the Admin API secret key.
+
## 2.2.1
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index e5d0f23c52..47eb0ade9d 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.2.1",
+ "version": "2.3.0",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 794424fbd8..890a989ca6 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -5,6 +5,7 @@ import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execaCommand } from 'execa'
import pc from 'picocolors'
+import { mintProjectCredentials } from '../config.js'
import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
import { detectProject } from '../context.js'
import { dockerCompose, rakeTask, streamLogs } from '../docker.js'
@@ -37,10 +38,15 @@ export function registerInitCommand(program: Command): void {
await rakeTask('db:seed', ctx.projectDir)
s.stop('Database seeded.')
- s.start('Configuring API key...')
- const apiKey = await fetchApiKey(ctx.projectDir)
- updateStorefrontEnv(ctx.projectDir, apiKey)
- s.stop(`API key: ${pc.cyan(apiKey)}`)
+ s.start('Configuring API keys...')
+ // Sequential, not Promise.all: finish the publishable key (and its
+ // storefront env write) before minting the secret, so a failure on the
+ // first step never leaves a freshly minted secret stranded on disk while
+ // init aborts.
+ const publishableKey = await fetchApiKey(ctx.projectDir)
+ updateStorefrontEnv(ctx.projectDir, publishableKey)
+ const secretKey = await mintCliCredentials(ctx.projectDir, ctx.port)
+ s.stop('API keys configured.')
if (flags.sampleData) {
s.start('Loading sample data...')
@@ -62,7 +68,12 @@ export function registerInitCommand(program: Command): void {
'',
pc.bold('Store API'),
` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/store`)}`,
- ` API Key: ${pc.cyan(apiKey)}`,
+ ` Publishable key: ${pc.cyan(publishableKey)}`,
+ '',
+ pc.bold('Admin API'),
+ ` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/admin`)}`,
+ ` Secret key: ${pc.cyan(secretKey)}`,
+ ` ${pc.dim('Saved to .spree/credentials.json')}`,
'',
].join('\n'),
'Your Spree store is ready!',
@@ -104,6 +115,22 @@ async function fetchApiKey(projectDir: string): Promise<string> {
return match[0]
}
+/**
+ * Mints a fresh read-only secret key into `.spree/credentials.json` so
+ * `spree api` works without a first-use minting round-trip.
+ *
+ * Always mints, overwriting any existing file: `init` reseeds the database
+ * immediately before this, so any previously stored key is presumptively
+ * orphaned (e.g. after a `docker compose down -v` wipe the host file survives
+ * but its DB row is gone). The lazy path in `resolveCredentials` is where a
+ * stored key is reused — there the database is intact.
+ */
+export async function mintCliCredentials(projectDir: string, port: number): Promise<string> {
+ // quiet: the init spinner owns the UI and prints the key in the setup summary.
+ const { token } = await mintProjectCredentials(projectDir, port, true)
+ return token
+}
+
export function updateStorefrontEnv(projectDir: string, apiKey: string): void {
const envPath = path.join(projectDir, 'apps', 'storefront', '.env.local')
if (!fs.existsSync(envPath)) return
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 98d3451fb2..6d6d2fde21 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -183,15 +183,22 @@ export function tokenPrefix(token: string): string {
* Auto-mints a read-only secret key through the project's dev stack and
* persists it in `.spree/credentials.json` (gitignored). Write scopes are
* never minted implicitly — `spree api-key create --scopes write_...` is the
- * explicit path.
+ * explicit path. Shared by the lazy path (`resolveCredentials`) and the eager
+ * path (`spree init`).
+ *
+ * @param quiet suppress the stderr progress chatter (the eager path owns its
+ * own spinner UI and prints the key in the setup summary).
*/
-async function mintProjectCredentials(
+export async function mintProjectCredentials(
projectDir: string,
port: number,
+ quiet = false,
): Promise<ProjectCredentials> {
- process.stderr.write(
- `${pc.dim('No credentials found — minting a read-only API key via the dev stack...')}\n`,
- )
+ if (!quiet) {
+ process.stderr.write(
+ `${pc.dim('No credentials found — minting a read-only API key via the dev stack...')}\n`,
+ )
+ }
let stdout: string
try {
@@ -221,7 +228,9 @@ async function mintProjectCredentials(
mintedAt: new Date().toISOString(),
}
writeProjectCredentials(projectDir, credentials)
- process.stderr.write(`${pc.dim(`Saved to .spree/credentials.json (scopes: read_all)`)}\n`)
+ if (!quiet) {
+ process.stderr.write(`${pc.dim(`Saved to .spree/credentials.json (scopes: read_all)`)}\n`)
+ }
return credentials
}
diff --git a/packages/cli/tests/init.test.ts b/packages/cli/tests/init.test.ts
index 3361622c46..a56fd5b6bc 100644
--- a/packages/cli/tests/init.test.ts
+++ b/packages/cli/tests/init.test.ts
@@ -4,22 +4,22 @@ import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { updateStorefrontEnv } from '../src/commands/init'
-describe('updateStorefrontEnv', () => {
- const tempDirs: string[] = []
+const tempDirs: string[] = []
- function makeTempDir(): string {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-init-test-'))
- tempDirs.push(dir)
- return dir
- }
+function makeTempDir(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-init-test-'))
+ tempDirs.push(dir)
+ return dir
+}
- afterEach(() => {
- for (const dir of tempDirs) {
- fs.rmSync(dir, { recursive: true, force: true })
- }
- tempDirs.length = 0
- })
+afterEach(() => {
+ for (const dir of tempDirs) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ tempDirs.length = 0
+})
+describe('updateStorefrontEnv', () => {
it('replaces placeholder key with real API key', () => {
const dir = makeTempDir()
const envPath = path.join(dir, 'apps', 'storefront')
diff --git a/packages/create-spree-app/.changeset/spree-credentials-gitignore.md b/packages/create-spree-app/.changeset/spree-credentials-gitignore.md
deleted file mode 100644
index 2159fa4277..0000000000
--- a/packages/create-spree-app/.changeset/spree-credentials-gitignore.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"create-spree-app": patch
----
-
-Scaffolded `.gitignore` now excludes `.spree/` — the local Admin API credentials directory used by `spree api` / `spree auth`.
diff --git a/packages/create-spree-app/CHANGELOG.md b/packages/create-spree-app/CHANGELOG.md
index 60a8d500ea..b7b1086796 100644
--- a/packages/create-spree-app/CHANGELOG.md
+++ b/packages/create-spree-app/CHANGELOG.md
@@ -1,5 +1,13 @@
# create-spree-app
+## 1.0.4
+
+### Patch Changes
+
+- Generated projects now document the Admin API CLI: `api`/`auth`/`api-key` passthrough scripts in `package.json`, an Admin API section in the README and CLAUDE.md showing `npx spree api get products` (works against the read-only key minted during setup), and the global-install option for a bare `spree` command.
+
+- Scaffolded `.gitignore` now excludes `.spree/` — the local Admin API credentials directory used by `spree api` / `spree auth`.
+
## 1.0.3
### Patch Changes
diff --git a/packages/create-spree-app/package.json b/packages/create-spree-app/package.json
index 3789e36fef..3db1d3484f 100644
--- a/packages/create-spree-app/package.json
+++ b/packages/create-spree-app/package.json
@@ -1,6 +1,6 @@
{
"name": "create-spree-app",
- "version": "1.0.3",
+ "version": "1.0.4",
"description": "Create a new Spree Commerce project with a single command",
"type": "module",
"bin": "./dist/index.js",
diff --git a/packages/create-spree-app/src/templates/claude-md.ts b/packages/create-spree-app/src/templates/claude-md.ts
index 8c4f79aeb4..46cf157233 100644
--- a/packages/create-spree-app/src/templates/claude-md.ts
+++ b/packages/create-spree-app/src/templates/claude-md.ts
@@ -70,6 +70,24 @@ export function rootClaudeMdContent(hasStorefront: boolean): string {
'',
'Read these files when you need Spree-specific guidance.',
'',
+ '## Querying the Admin API',
+ '',
+ 'Project setup mints a read-only secret key into `.spree/credentials.json`',
+ '(gitignored) — and `spree api` mints it on first use if setup was skipped —',
+ 'so the Admin API client works without further configuration. Use it to',
+ 'inspect live data instead of guessing at the schema:',
+ '',
+ '```bash',
+ 'npx spree api get products # list products',
+ 'npx spree api get "orders?q[state_eq]=complete" # Ransack filters',
+ 'npx spree api endpoints # every endpoint + its required scope',
+ 'npx spree api schema "POST /products" # request/response schema for an operation',
+ '```',
+ '',
+ 'The default key is read-only. For writes, create a scoped key and pass it via',
+ '`SPREE_API_KEY`: `npx spree api-key create --scopes write_products`, then',
+ "`SPREE_API_KEY=sk_... npx spree api post products --data '{...}'`.",
+ '',
'## Common Commands',
'',
'```bash',
@@ -77,6 +95,7 @@ export function rootClaudeMdContent(hasStorefront: boolean): string {
'npm run stop # Stop services',
'npm run console # Rails console',
'npm run logs # Backend logs',
+ 'npx spree api get products # Query the Admin API (read-only key preconfigured)',
'npx spree eject # Switch to local backend builds',
'```',
'',
diff --git a/packages/create-spree-app/src/templates/package-json.ts b/packages/create-spree-app/src/templates/package-json.ts
index 896b270231..734a610ef3 100644
--- a/packages/create-spree-app/src/templates/package-json.ts
+++ b/packages/create-spree-app/src/templates/package-json.ts
@@ -13,6 +13,9 @@ export function rootPackageJsonContent(name: string): string {
seed: 'spree seed',
'load-sample-data': 'spree sample-data',
console: 'spree console',
+ api: 'spree api',
+ auth: 'spree auth',
+ 'api-key': 'spree api-key',
},
dependencies: {
'@spree/cli': '^2.0.0',
diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.ts
index d59dd75fd7..a0a9475368 100644
--- a/packages/create-spree-app/src/templates/readme.ts
+++ b/packages/create-spree-app/src/templates/readme.ts
@@ -89,6 +89,37 @@ This project uses [\`@spree/cli\`](https://www.npmjs.com/package/@spree/cli) to
| \`spree api-key list\` | List all API keys |
| \`spree api-key revoke <token>\` | Revoke an API key |
+### Admin API
+
+Project setup mints a read-only secret key into \`.spree/credentials.json\` (gitignored), so the Admin API client works out of the box. If you skipped the setup step, \`spree api\` mints the key on first use instead:
+
+\`\`\`bash
+npx spree api get products
+npx spree api get "orders?q[state_eq]=complete"
+npx spree api endpoints # list endpoints + required scopes
+npx spree api status # show resolved credentials + server reachability
+\`\`\`
+
+The pre-configured key is read-only. To write, create a scoped secret key and pass it via \`SPREE_API_KEY\`:
+
+\`\`\`bash
+npx spree api-key create --scopes write_products
+SPREE_API_KEY=sk_... npx spree api post products --data '{"name":"New product"}'
+\`\`\`
+
+| Command | Description |
+|---------|-------------|
+| \`spree api get/post/patch/delete <path>\` | Call the Admin API directly |
+| \`spree api endpoints\` | List Admin API endpoints with required scopes |
+| \`spree auth login --profile <name>\` | Save named credentials for a remote store |
+
+> **Running \`spree\` directly.** The commands above use \`npx\` because \`@spree/cli\` is a local project dependency. You can also run any of the package scripts (e.g. \`npm run api -- get products\`), or install the CLI globally for a bare \`spree\` command:
+>
+> \`\`\`bash
+> npm install -g @spree/cli
+> spree api get products
+> \`\`\`
+
## Learn More
- [Spree Documentation](https://docs.spreecommerce.org)
diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.ts
index cbd3969c7d..ae54a2d66d 100644
--- a/packages/create-spree-app/tests/templates.test.ts
+++ b/packages/create-spree-app/tests/templates.test.ts
@@ -64,6 +64,13 @@ describe('rootPackageJsonContent', () => {
expect(pkg.scripts.down).toContain('docker compose')
})
+ it('exposes the Admin API command groups as scripts', () => {
+ const pkg = JSON.parse(rootPackageJsonContent('my-store'))
+ expect(pkg.scripts.api).toBe('spree api')
+ expect(pkg.scripts.auth).toBe('spree auth')
+ expect(pkg.scripts['api-key']).toBe('spree api-key')
+ })
+
it('includes @spree/cli as a dependency', () => {
const pkg = JSON.parse(rootPackageJsonContent('my-store'))
expect(pkg.dependencies['@spree/cli']).toBeDefined()
@@ -116,6 +123,14 @@ describe('readmeContent', () => {
expect(content).toContain('http://localhost:4567/admin')
expect(content).toContain('http://localhost:4567/api/v3/store')
})
+
+ it('documents the Admin API and how to run the CLI directly', () => {
+ const content = readmeContent('my-store', true, 3000)
+ expect(content).toContain('### Admin API')
+ expect(content).toContain('npx spree api get products')
+ expect(content).toContain('.spree/credentials.json')
+ expect(content).toContain('npm install -g @spree/cli')
+ })
})
describe('gitignoreContent', () => {