JavaScriptやNode.jsのアプリケーションからmicroCMSのAPIと簡単に通信できます。
このSDKの現在の保守レベルはActiveです。
詳細はSDKの保守方針をご覧ください。
- Node.js 18+(22+を推奨、ブラウザから利用する場合は不要)
- TypeScript6.0+(型を利用する場合)
まず簡単な組み込みを試したい場合は、公式のJavaScriptチュートリアルを参照してください。ブラウザとNode.jsでの基本的な利用手順を確認できます。
$ npm install microcms-js-sdk
または
$ yarn add microcms-js-sdkリリースページからmicrocms-js-sdk-x.y.z.tgzをダウンロードして解凍してください。その後、お好みのサーバーにアップロードして使用してください。対象ファイルは ./dist/umd/microcms-js-sdk.js です。
<script src="./microcms-js-sdk.js"></script>外部プロバイダーが提供するURLを読み込んでご利用ください。
<script src="https://cdn.jsdelivr.net/npm/microcms-js-sdk@3.1.1/dist/umd/microcms-js-sdk.min.js"></script>または
<script src="https://cdn.jsdelivr.net/npm/microcms-js-sdk/dist/umd/microcms-js-sdk.min.js"></script>Warning
ホスティングサービス(cdn.jsdelivr.net)はmicroCMSとは関係ありません。本番環境でのご利用には、お客様のサーバーでのセルフホスティングをお勧めします。
const { createClient } = require('microcms-js-sdk'); // CommonJSまたは
import { createClient } from 'microcms-js-sdk'; //ES6<script>
const { createClient } = microcms;
</script>// クライアントオブジェクトを作成します。
const client = createClient({
serviceDomain: 'YOUR_DOMAIN', // YOUR_DOMAINはXXXX.microcms.ioのXXXXの部分です。
apiKey: 'YOUR_API_KEY',
// retry: true // 最大2回まで再試行します。
});TypeScriptでの型指定と推論はTypeScriptを参照してください。
以下の表は、microCMS JavaScript SDKの各メソッドがリスト形式のAPIまたはオブジェクト形式のAPI、どちらで使用できるかを示しています。
| メソッド | リスト形式 | オブジェクト形式 |
|---|---|---|
| getList | ✅ | |
| getListDetail | ✅ | |
| getObject | ✅ | |
| getAllContentIds | ✅ | |
| getAllContents | ✅ | |
| create | ✅ | |
| update | ✅ | ✅ |
| delete | ✅ |
Note
汎用の取得メソッドgetは非推奨です。getList・getListDetail・getObjectを使用してください。スキーマを指定したクライアントでも、getの戻り値型は自動推論されません。
getListメソッドは、指定されたエンドポイントからコンテンツ一覧を取得するために使用します。
client
.getList({
endpoint: 'endpoint',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));queriesプロパティを使用して、特定の条件に一致するコンテンツ一覧を取得できます。利用可能な各プロパティの詳細については、microCMSのドキュメントを参照してください。
client
.getList({
endpoint: 'endpoint',
queries: {
draftKey: 'abcd',
limit: 100,
offset: 1,
orders: 'createdAt',
q: 'こんにちは',
fields: 'id,title',
ids: 'foo',
filters: 'publishedAt[greater_than]2021-01-01T03:00:00.000Z',
depth: 1,
},
})
.then((res) => console.log(res))
.catch((err) => console.error(err));getListDetailメソッドは、指定されたエンドポイントから、IDで指定された単一コンテンツを取得するために使用します。
client
.getListDetail({
endpoint: 'endpoint',
contentId: 'contentId',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));queriesプロパティを使用して、特定の条件に一致する単一コンテンツを取得できます。利用可能な各プロパティの詳細については、microCMSのドキュメントを参照してください。
client
.getListDetail({
endpoint: 'endpoint',
contentId: 'contentId',
queries: {
draftKey: 'abcd',
fields: 'id,title',
depth: 1,
},
})
.then((res) => console.log(res))
.catch((err) => console.error(err));getObjectメソッドは、指定されたエンドポイントからオブジェクト形式のコンテンツを取得するために使用します。
client
.getObject({
endpoint: 'endpoint',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));getAllContentIdsメソッドは、指定されたエンドポイントからコンテンツIDのみを全件取得するために使用します。
client
.getAllContentIds({
endpoint: 'endpoint',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));filtersプロパティを使用することで、条件に一致するコンテンツIDを全件取得できます。
client
.getAllContentIds({
endpoint: 'endpoint',
filters: 'category[equals]uN28Folyn',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));draftKeyプロパティを使用することで、下書き中のコンテンツのIDを全件取得できます。
client
.getAllContentIds({
endpoint: 'endpoint',
draftKey: 'draftKey',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));alternateFieldプロパティにフィールドIDを指定することで、コンテンツID以外のフィールドの値を全件取得できます。取得した値が文字列でない場合は、実行時にエラーになります。
client
.getAllContentIds({
endpoint: 'endpoint',
alternateField: 'url',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));getAllContentsメソッドは、指定されたエンドポイントから、コンテンツを全件取得するために使用します。
client
.getAllContents({
endpoint: 'endpoint',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));queriesプロパティを使用して、特定の条件に一致するすべてのコンテンツを取得できます。利用可能な各プロパティの詳細については、microCMSのドキュメントを参照してください。
client
.getAllContents({
endpoint: 'endpoint',
queries: {
filters: 'createdAt[greater_than]2021-01-01T03:00:00.000Z',
orders: '-createdAt',
},
})
.then((res) => console.log(res))
.catch((err) => console.error(err));createメソッドは指定されたエンドポイントにコンテンツを登録するために使用します。
client
.create({
endpoint: 'endpoint',
content: {
title: 'タイトル',
body: '本文',
},
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));contentIdプロパティを使用することで、指定されたIDでコンテンツを登録できます。
client
.create({
endpoint: 'endpoint',
contentId: 'contentId',
content: {
title: 'タイトル',
body: '本文',
},
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));isDraftプロパティを使用することで、下書き中のステータスでコンテンツを登録できます。
client
.create({
endpoint: 'endpoint',
content: {
title: 'タイトル',
body: '本文',
},
isDraft: true,
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));contentIdプロパティとisDraftプロパティを使用することで、指定されたIDかつ下書き中のステータスでコンテンツを登録できます。
client
.create({
endpoint: 'endpoint',
contentId: 'contentId',
content: {
title: 'タイトル',
body: '本文',
},
isDraft: true,
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));isClosedプロパティを使用することで、公開終了のステータスでコンテンツを登録できます。
注:
isDraftとisClosedは同時にtrueにできません。両方をtrueで渡すと、SDK はランタイムでエラーとして拒否します。isClosed: trueを使う場合は、isDraftを省略、またはfalseを設定してください。
client
.create({
endpoint: 'endpoint',
content: {
title: 'タイトル',
body: '本文',
},
isClosed: true,
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));contentIdプロパティとisClosedプロパティを使用することで、指定されたIDかつ公開終了のステータスでコンテンツを登録できます。上記と同様、isDraft と isClosed を同時に true にすることはできません。
client
.create({
endpoint: 'endpoint',
contentId: 'contentId',
content: {
title: 'タイトル',
body: '本文',
},
isClosed: true,
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));updateメソッドは特定のコンテンツを編集するために使用します。
client
.update({
endpoint: 'endpoint',
contentId: 'contentId',
content: {
title: 'タイトル',
},
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));isDraft プロパティを指定することで、コンテンツを下書き状態で更新することができます。
client
.update({
endpoint: 'endpoint',
contentId: 'contentId',
content: {
title: 'タイトル',
},
isDraft: true,
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));APIの型がオブジェクト形式のコンテンツを編集する場合は、contentIdプロパティを使用せずに、エンドポイントのみを指定します。
client
.update({
endpoint: 'endpoint',
content: {
title: 'タイトル',
},
})
.then((res) => console.log(res.id))
.catch((err) => console.error(err));deleteメソッドは指定されたエンドポイントから特定のコンテンツを削除するために使用します。
client
.delete({
endpoint: 'endpoint',
contentId: 'contentId',
})
.catch((err) => console.error(err));Next.jsのApp Routerで利用されるfetchのcacheオプションを指定できます。
指定可能なオプションは、Next.jsの公式ドキュメントを参照してください。
const response = await client.getList({
customRequestInit: {
next: {
revalidate: 60,
},
},
endpoint: 'endpoint',
});fetchリクエストを中断できます。
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, 1000);
try {
const response = await client.getObject({
customRequestInit: {
signal: controller.signal,
},
endpoint: 'config',
});
} finally {
clearTimeout(timeoutId);
}補完や推論をエディタで試す場合は、型付きクライアントの利用例を参照してください。
コンテンツAPIの型は、サービス全体のスキーマをクライアント生成時に指定する方法と、メソッドごとに型を指定する方法があります。取得クエリに対応したコンテンツ型だけを取り出すこともできます。
microcms-typegenで作成したサービスのスキーマ型を渡すと、TypeScriptのコンパイル時に次の型検査・推論が利用できます。
- 入力の型検査:登録済みのエンドポイントとAPI形式、静的に確定する
fieldsのフィールドパスとdepthの組み合わせを検査します。クエリの項目名、値の基本型、depthの範囲(0〜3)も検査します。 - 戻り値型の推論:エンドポイントと
depth・fieldsに応じて、getList、getListDetail、getObject、getAllContentsの戻り値型を推論します。
以下は型生成器の設定がservices.mainの場合の例です。スキーマ型の名前はサービス名に応じて変わります。
import { createClient } from 'microcms-js-sdk';
import type { MainServiceSchema } from './microcms-types';
const client = createClient<MainServiceSchema>({
serviceDomain: 'YOUR_DOMAIN',
apiKey: 'YOUR_API_KEY',
});
const response = await client.getList({
endpoint: 'blogs',
queries: { depth: 2, fields: ['title', 'category.name'] },
});以下の項目は型検査・推論には未対応です。今後対応を検討します。
| 項目 | 検査・推論しない内容 |
|---|---|
filters |
フィールド名・演算子・値の正しさ |
orders |
フィールド名・並び順指定の正しさ |
alternateField |
指定先フィールドの存在と値の型 |
richEditorFormat: 'object' |
戻り値型の自動推論。利用時はメソッドの型引数が必要(省略すると型エラー) |
従来どおり、スキーマ型を渡さずにクライアントを作成し、読み取りメソッドの型引数を指定できます。型付きクライアントでも明示的なメソッド型引数を使用できます。この呼び出しではスキーマによるdepth・fieldsの型推論より指定した型を優先します。指定した型と実際のレスポンスが一致するかは利用側で確認してください。
import { createClient } from 'microcms-js-sdk';
type Content = { title: string };
const client = createClient({
serviceDomain: 'YOUR_DOMAIN',
apiKey: 'YOUR_API_KEY',
});
const list = await client.getList<Content>({ endpoint: 'blogs' });
const detail = await client.getListDetail<Content>({
endpoint: 'blogs',
contentId: 'blog-id',
});
const object = await client.getObject<Content>({ endpoint: 'settings' });コンポーネントのpropsなどで、取得時と同じクエリに対応したコンテンツ1件の型が必要な場合はInferMicroCMSContentを使います。
import { createClient, type InferMicroCMSContent } from 'microcms-js-sdk';
import type { MainServiceSchema } from './microcms-types';
const client = createClient<MainServiceSchema>({
serviceDomain: 'YOUR_DOMAIN',
apiKey: 'YOUR_API_KEY',
});
const queries = { depth: 2, fields: ['title', 'category.name'] } as const;
const response = await client.getList({ endpoint: 'blogs', queries });
type BlogCardProps = {
blog: InferMicroCMSContent<MainServiceSchema, 'blogs', typeof queries>;
};このようにクエリを変数に分ける場合は、as constでdepthとfieldsの具体的な値を保持します。const queries = { ... }だけではdepthはnumber、fieldsはstring[]に広がります。メソッドへクエリを直接書く場合はas constは不要です。
InferMicroCMSContentだけで不正なfieldsの型を宣言しても、その場では型エラーにならず、結果はunknownです。同じクエリを型付きクライアントへ渡すと、静的に分かる誤記は呼び出し箇所で型エラーになります。
型生成器で作成したMainServiceSchemaを指定すると、create・updateのendpointからフィールド名と値の型を推論します。参照はコンテンツID、画像とファイルはURL文字列を指定します。create・deleteはリスト形式API、updateはリスト形式・オブジェクト形式APIで利用できます。deleteもエンドポイントを型検査します。
import { createClient } from 'microcms-js-sdk';
import type { MainServiceSchema } from './microcms-types';
const client = createClient<MainServiceSchema>({
serviceDomain: 'YOUR_DOMAIN',
apiKey: 'YOUR_API_KEY',
});
await client.create({
endpoint: 'blogs',
content: { title: 'タイトル', category: 'category-id' },
});
await client.update({
endpoint: 'blogs',
contentId: 'blog-id',
content: { title: '更新したタイトル' },
});
await client.delete({ endpoint: 'blogs', contentId: 'blog-id' });生成された入力型はMainServiceSchema['blogs']['create']やMainServiceSchema['blogs']['update']として取り出せます。
従来のcreate<Content>・update<Content>も利用できます。型付きクライアントで明示すると、その呼び出しでは生成スキーマの書き込み型より指定した型を優先します。create<Content>はContent、update<Content>はPartial<Content>としてcontentを検査します。指定した型とAPIスキーマの一致は利用側で確認してください。
type TitleOnly = { title: string };
await client.update<TitleOnly>({
endpoint: 'blogs',
contentId: 'blog-id',
content: { title: '更新したタイトル' },
});const readClient = createClient({
serviceDomain: 'serviceDomain',
apiKey: 'readApiKey',
});
const writeClient = createClient({
serviceDomain: 'serviceDomain',
apiKey: 'writeApiKey',
});const { createManagementClient } = require('microcms-js-sdk'); // CommonJSまたは
import { createManagementClient } from 'microcms-js-sdk'; //ES6<script>
const { createManagementClient } = microcms;
</script>const client = createManagementClient({
serviceDomain: 'YOUR_DOMAIN', // YOUR_DOMAINはXXXX.microcms.ioのXXXXの部分です。
apiKey: 'YOUR_API_KEY',
});メディアに画像やファイルをアップロードできます。
// Blob
import { readFileSync } from 'fs';
const file = readFileSync('path/to/file');
client
.uploadMedia({
data: new Blob([file], { type: 'image/png' }),
name: 'image.png',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));
// or ReadableStream
import { createReadStream } from 'fs';
import { Stream } from 'stream';
const file = createReadStream('path/to/file');
client
.uploadMedia({
data: Stream.Readable.toWeb(file),
name: 'image.png',
type: 'image/png',
})
.then((res) => console.log(res))
.catch((err) => console.error(err));
// or URL
client
.uploadMedia({
data: 'https://example.com/image.png',
// name: 'image.png', ← 任意
})
.then((res) => console.log(res))
.catch((err) => console.error(err));// File
const file = document.querySelector('input[type="file"]').files[0];
client
.uploadMedia({
data: file,
})
.then((res) => console.log(res))
.catch((err) => console.error(err));
// or URL
client
.uploadMedia({
data: 'https://example.com/image.png',
// name: 'image.png', ← 任意
})
.then((res) => console.log(res))
.catch((err) => console.error(err));マネジメントAPIのuploadMediaは、次の形式のデータを受け取ります。
type UploadMediaRequest =
| { data: File }
| { data: Blob; name: string }
| { data: ReadableStream; name: string; type: `image/${string}` }
| {
data: URL | string;
name?: string | null | undefined;
customRequestHeaders?: HeadersInit;
};
function uploadMedia(params: UploadMediaRequest): Promise<{ url: string }>;コンテンツAPIとマネジメントAPIのどちらでも、SDKが生成したリクエストエラーは通常のErrorとして扱えます。console.error(error)でエラーメッセージとスタックトレースを出力でき、HTTPエラーの場合はHTTPステータスとAPIから返されたエラーメッセージも含まれます。
SDKが生成したリクエストエラーは、両クライアントで共通のisMicroCMSRequestErrorを使って判定できます。判定後はstatus、url、originalErrorを個別に参照できます。以下はコンテンツAPIの例です。マネジメントAPIのuploadMediaでも、microCMSへのリクエストでSDKが生成したエラーは同様に判定できます。
import { createClient, isMicroCMSRequestError } from 'microcms-js-sdk';
const client = createClient({
serviceDomain: 'serviceDomain',
apiKey: 'apiKey',
});
try {
await client.getList({ endpoint: 'blog' });
} catch (error) {
// エラーメッセージとスタックトレースを出力します
console.error(error);
if (isMicroCMSRequestError(error)) {
// 必要に応じてリクエストに関する追加情報を参照できます
console.log(error.status);
console.log(error.url);
console.log(error.originalError);
}
}| プロパティ | HTTPエラー | ネットワークエラー |
|---|---|---|
status |
HTTPステータスコード | undefined |
url |
リクエスト先URL | リクエスト先URL |
originalError |
undefined |
fetchが投げた元の値 |
uploadMediaの引数検証やアップロード元URLの取得で起きたエラーは、microCMSへのリクエスト前に発生するため、isMicroCMSRequestErrorで判定できない場合があります。
urlにdraftKeyが含まれる場合、その値は***にマスクされます。リクエストヘッダー、リクエストボディ、Responseオブジェクトはエラーへ追加されません。
originalErrorの内容はNode.js、ブラウザ、Edge Runtimeなどの実行環境によって異なり、SDKとして形式を保証しません。
追加されるプロパティは非列挙です。そのため、既存のmessage、toString()、Object.keys()、JSON.stringify()の結果には影響しません。
SDKの開発環境・テスト・fixture・CIについては、開発ガイドを参照してください。
Apache-2.0