{"id":21169028,"url":"https://github.com/cosmicjs/cosmic-sdk-js","last_synced_at":"2025-07-06T11:37:57.435Z","repository":{"id":176404581,"uuid":"615388412","full_name":"cosmicjs/cosmic-sdk-js","owner":"cosmicjs","description":"The official JavaScript SDK for Cosmic.  Use it to power content server-side, in the browser, and in native apps.","archived":false,"fork":false,"pushed_at":"2025-05-30T18:40:09.000Z","size":406,"stargazers_count":15,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-05-31T03:04:02.868Z","etag":null,"topics":["api","content-management","cosmicjs","headless-cms","javascript","nodejs"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@cosmicjs/sdk","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cosmicjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-03-17T15:22:44.000Z","updated_at":"2025-05-30T18:39:11.000Z","dependencies_parsed_at":"2024-06-21T17:41:58.286Z","dependency_job_id":"228acd09-46be-4ac5-91b0-db07434a5b99","html_url":"https://github.com/cosmicjs/cosmic-sdk-js","commit_stats":null,"previous_names":["cosmicjs/cosmic-sdk-js"],"tags_count":20,"template":false,"template_full_name":null,"purl":"pkg:github/cosmicjs/cosmic-sdk-js","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cosmicjs%2Fcosmic-sdk-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cosmicjs%2Fcosmic-sdk-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cosmicjs%2Fcosmic-sdk-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cosmicjs%2Fcosmic-sdk-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cosmicjs","download_url":"https://codeload.github.com/cosmicjs/cosmic-sdk-js/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cosmicjs%2Fcosmic-sdk-js/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263895884,"owners_count":23526747,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","content-management","cosmicjs","headless-cms","javascript","nodejs"],"created_at":"2024-11-20T15:21:52.815Z","updated_at":"2025-07-06T11:37:57.428Z","avatar_url":"https://github.com/cosmicjs.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ca href=\"https://app.cosmicjs.com/signup\"\u003e\n  \u003cimg src=\"https://imgix.cosmicjs.com/ca74e2f0-c8e4-11ed-b01d-23d7b265c299-cosmic-dashboard-dark.png?w=2000\u0026auto=format\" alt=\"Cosmic dashboard darkmode\" /\u003e\n\u003c/a\u003e\n\n\u003ch1 align=\"center\"\u003eCosmic JavaScript SDK\u003c/h1\u003e\n\n[Cosmic](https://www.cosmicjs.com/) is a [headless CMS](https://www.cosmicjs.com/headless-cms) (content management system) that provides a web dashboard to create content and an API toolkit to deliver content to any website or application. Nearly any type of content can be built using the dashboard and delivered using this SDK.\n\n[Get started free →](https://app.cosmicjs.com/signup)\n\n## Install\n\nInstall the Cosmic JavaScript SDK. We recommend using the [bun](https://bun.sh) package manager.\n\n```bash\nbun add @cosmicjs/sdk\n# OR\nyarn add @cosmicjs/sdk\n# OR\nnpm install @cosmicjs/sdk\n```\n\n## Import\n\nImport Cosmic into your app using the `createBucketClient` method.\n\n```jsx\nimport { createBucketClient } from '@cosmicjs/sdk';\n```\n\n## Authentication\n\nIn the [Cosmic admin dashboard](https://app.cosmicjs.com/login) go to _Bucket \u003e Settings \u003e API Access_ and get your Bucket slug and read key then set the variables in your app to connect to your Bucket.\n\n```jsx\nconst cosmic = createBucketClient({\n  bucketSlug: 'BUCKET_SLUG',\n  readKey: 'BUCKET_READ_KEY',\n});\n```\n\n## Get Objects\n\nObjects are the basic building blocks of content in Cosmic.\n\n### Get multiple Objects [[see docs](https://www.cosmicjs.com/docs/api/objects#get-objects)]\n\nUse the `objects.find()` method to fetch Objects.\n\n```jsx\nconst posts = await cosmic.objects\n  .find({\n    type: 'posts',\n  })\n  .props(['title', 'slug', 'metadata'])\n  .limit(10);\n```\n\nThe above example fetches Objects in the `posts` Object type returning the `title`, `slug`, and `metadata` properties, limiting the response to `10` Objects.\n\n### Get single Object by slug [[see docs](https://www.cosmicjs.com/docs/api/objects#get-a-single-object-by-slug)]\n\nUse the `objects.findOne()` method with `type` and `slug` to fetch a single Object.\n\n```jsx\nconst post = await cosmic.objects\n  .findOne({\n    type: 'pages',\n    slug: 'home',\n  })\n  .props(['title', 'slug', 'metadata']);\n```\n\n## Create, update, and delete Objects\n\nTo write to the Cosmic API, you will need to set the Bucket write key found in _Bucket \u003e Settings \u003e API Access_. (NOTE: never expose your write key in any client-side code)\n\n```jsx\nconst cosmic = createBucketClient({\n  bucketSlug: 'BUCKET_SLUG',\n  readKey: 'BUCKET_READ_KEY',\n  writeKey: 'BUCKET_WRITE_KEY',\n});\n```\n\n### Create Object [[see docs](https://www.cosmicjs.com/docs/api/objects#create-an-object)]\n\nUse the `objects.insertOne()` method to create an Object.\n\n```jsx\nawait cosmic.objects.insertOne({\n  title: 'Blog Post Title',\n  type: 'posts',\n  metadata: {\n    content: 'Here is the blog post content... still learning',\n    seo_description: 'This is the blog post SEO description.',\n    featured_post: true,\n    tags: ['javascript', 'cms'],\n  },\n});\n```\n\n### Update Object [[see docs](https://www.cosmicjs.com/docs/api/objects#update-an-object)]\n\nUse the `objects.updateOne()` method to update an Object by specifying the Object `id` and include properties that you want to update.\n\n```jsx\nawait cosmic.objects.updateOne('5ff75368c2dfa81a91695cec', {\n  metadata: {\n    content: 'This is the updated blog post content... I got it now!',\n    featured_post: false,\n  },\n});\n```\n\n### Delete Object [[see docs](https://www.cosmicjs.com/docs/api/objects#delete-an-object)]\n\nUse the `objects.deleteOne()` method to delete an Object by specifying the Object `id`.\n\n```jsx\nawait cosmic.objects.deleteOne('5ff75368c2dfa81a91695cec');\n```\n\n## AI Capabilities\n\nCosmic provides AI-powered text and image generation capabilities through the SDK.\n\n### Generate Text [[see docs](https://www.cosmicjs.com/docs/api/ai#generate-text)]\n\nUse the `ai.generateText()` method to generate text content using AI models. You must provide either a `prompt` or `messages` parameter.\n\n#### Using a simple prompt:\n\n```jsx\nconst textResponse = await cosmic.ai.generateText({\n  prompt: 'Write a product description for a coffee mug',\n  max_tokens: 500, // optional\n});\n\nconsole.log(textResponse.text);\nconsole.log(textResponse.usage); // { input_tokens: 10, output_tokens: 150 }\n```\n\n#### Using messages for chat-based models:\n\n```jsx\nconst chatResponse = await cosmic.ai.generateText({\n  messages: [\n    { role: 'user', content: 'Tell me about coffee mugs' },\n    {\n      role: 'assistant',\n      content: 'Coffee mugs are vessels designed to hold hot beverages...',\n    },\n    { role: 'user', content: 'What materials are they typically made from?' },\n  ],\n  max_tokens: 500, // optional\n});\n\nconsole.log(chatResponse.text);\nconsole.log(chatResponse.usage);\n```\n\n#### Using streaming for real-time responses:\n\n```jsx\nimport { TextStreamingResponse } from '@cosmicjs/sdk';\n\n// Enable streaming with the stream: true parameter\nconst result = await cosmic.ai.generateText({\n  prompt: 'Tell me about coffee mugs',\n  // or use messages array format\n  max_tokens: 500,\n  stream: true // Enable streaming\n});\n\n// Cast the result to TextStreamingResponse\nconst stream = result as TextStreamingResponse;\n\n// Option 1: Event-based approach\nlet fullResponse = '';\nstream.on('text', (text) =\u003e {\n  fullResponse += text;\n  process.stdout.write(text); // Display text as it arrives\n});\nstream.on('usage', (usage) =\u003e console.log('Usage:', usage));\nstream.on('end', (data) =\u003e console.log('Complete:', fullResponse));\nstream.on('error', (error) =\u003e console.error('Error:', error));\n\n// Option 2: For-await loop approach\nasync function processStream() {\n  let fullResponse = '';\n  try {\n    for await (const chunk of stream) {\n      if (chunk.text) {\n        fullResponse += chunk.text;\n        process.stdout.write(chunk.text);\n      }\n    }\n    console.log('\\nComplete text:', fullResponse);\n  } catch (error) {\n    console.error('Error:', error);\n  }\n}\n```\n\n#### Using the simplified stream method\n\n```jsx\n// Simplified streaming method\nconst stream = await cosmic.ai.stream({\n  prompt: 'Tell me about coffee mugs',\n  max_tokens: 500,\n});\n\n// Process stream using events or for-await loop as shown above\n```\n\nThe `TextStreamingResponse` supports two usage patterns:\n\n1. **Event-based**: Extends EventEmitter with these events:\n\n   - `text`: New text fragments\n   - `usage`: Token usage information\n   - `end`: Final data when stream completes\n   - `error`: Stream errors\n\n2. **AsyncIterator**: For for-await loops, with chunk objects containing:\n   - `text`: Text fragments\n   - `usage`: Token usage information\n   - `end`: Set to true for the final chunk\n   - `error`: Error information\n\n### Analyze Images and Files\n\nThe AI model can analyze images and files when generating text responses. This feature works with both the `prompt` and `messages` approaches.\n\n```jsx\nconst textWithImageResponse = await cosmic.ai.generateText({\n  prompt: 'Describe this coffee mug and suggest improvements to its design',\n  media_url: 'https://imgix.cosmicjs.com/your-image-url.jpg',\n  max_tokens: 500,\n});\n\nconsole.log(textWithImageResponse.text);\nconsole.log(textWithImageResponse.usage);\n```\n\n### Generate Image [[see docs](https://www.cosmicjs.com/docs/api/ai#generate-image)]\n\nUse the `ai.generateImage()` method to create AI-generated images based on text prompts.\n\n```jsx\nconst imageResponse = await cosmic.ai.generateImage({\n  prompt: 'A serene mountain landscape at sunset',\n  // Optional parameters\n  metadata: { tags: ['landscape', 'mountains', 'sunset'] },\n  folder: 'ai-generated-images',\n  alt_text: 'A beautiful mountain landscape with a colorful sunset',\n});\n\n// Access the generated image properties\nconsole.log(imageResponse.media.url); // Direct URL to the generated image\nconsole.log(imageResponse.media.imgix_url); // Imgix-enhanced URL for additional transformations\nconsole.log(imageResponse.media.width); // Image width\nconsole.log(imageResponse.media.height); // Image height\nconsole.log(imageResponse.media.alt_text); // Alt text for the image\nconsole.log(imageResponse.revised_prompt); // Potentially revised prompt used by the AI\n```\n\n## Learn more\n\nGo to the [Cosmic docs](https://www.cosmicjs.com/docs) to learn more capabilities.\n\n## Community support\n\nFor additional help, you can use one of these channels to ask a question:\n\n- [Discord](https://discord.gg/MSCwQ7D6Mg) (Development questions, bug reports)\n- [GitHub](https://github.com/cosmicjs/cosmic-sdk-js) (Issues, contributions)\n- [X (formerly Twitter)](https://twitter.com/cosmicjs) (Get the latest news about Cosmic features and notifications)\n- [YouTube](https://www.youtube.com/cosmicjs) (Learn from video tutorials)\n\n## Cosmic support\n\n- [Contact us](https://www.cosmicjs.com/contact) for help with any service questions and custom plan inquiries.\n\n## Contributing\n\nThis project uses [changeset](https://www.npmjs.com/package/@changesets/cli) to manage releases. Follow the following steps to add a changeset:\n\n- Run `npm run changeset` command and select type of release with description of changes.\n- When PR with changeset is merged into `main` branch, Github will create a new PR with correct version change and changelog edits.\n- When `codeowner` merges the generated PR, it will publish the package and create a Github release.\n\n## License\n\nThis project is published under the [MIT](https://github.com/cosmicjs/cosmic-sdk-js/blob/HEAD/LICENSE) license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcosmicjs%2Fcosmic-sdk-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcosmicjs%2Fcosmic-sdk-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcosmicjs%2Fcosmic-sdk-js/lists"}