xAI Integration
Learn how to upload images from xAI Grok image generation directly to easyCDN with the Node.js SDK.
xAI uses OpenAI client
Please note that xAI uses the OpenAI client for image generation, as described in the official xAI documentation. You can find the official xAI documentation here.
Installation
Install both the easyCDN Node.js SDK and the official OpenAI SDK:
bash
npm install @easycdn/server openaiUsage
typescript
import { createClient } from '@easycdn/server'
import dayjs from 'dayjs'
import OpenAI from 'openai'
const easyCdnClient = createClient({
secretKey: process.env.EASYCDN_SECRET_KEY!,
})
const xAiClient = new OpenAI({
apiKey: process.env.XAI_API_KEY!,
baseURL: 'https://api.x.ai/v1',
})
// generate image(s) with xAI
const response = await xAiClient.images.generate({
model: 'grok-2-image',
prompt: 'A lake with a mountain in the background',
n: 2,
})
// Upload all images to easyCDN
const uploadedAssets = await easyCdnClient.uploadFromOpenAi(response, {
expiresAt: dayjs().add(1, 'day').toISOString(),
fileNamePrefix: 'xai-lake',
})
console.log('Uploaded assets:')
for (const asset of uploadedAssets) {
console.log(`- ${asset.asset.name}: ${asset.asset.url}`)
}Extended Usage
You can also use the uploadFromOpenAi() method with additional options. You can give a custom name to each image, set a prefix for the filename, set the expiration date, and transform the image. The expiration date and transform options are the same as with normal uploads. See the API reference for more details.
typescript
const uploadedAssets = await easyCdnClient.uploadFromOpenAi(response, {
fileNamePrefix: 'openai-sunset',
expiresAt: dayjs().add(1, 'day').toISOString(),
transform: {
image: {
width: 642,
format: 'webp',
},
},
})
API Reference
For complete API documentation including all options (custom naming, transformations, expiration, progress tracking), see the uploadFromOpenAi() reference.