Integrate Mastra in your SvelteKit project
Mastra integrates with SvelteKit, making it easy to:
- Build flexible APIs to serve AI-powered features
- Simplify deployment with a unified codebase for frontend and backend
- Take advantage of SvelteKit's built-in Actions or Server Endpoints for efficient server-client workflows
Use this guide to scaffold and integrate Mastra with your SvelteKit project.
- Actions
- Server Endpoints
Install Mastra
Install the required Mastra packages:
- npm
- yarn
- pnpm
- bun
npm install mastra@latest @mastra/core@latest @mastra/libsql@latestyarn add mastra@latest @mastra/core@latest @mastra/libsql@latestpnpm add mastra@latest @mastra/core@latest @mastra/libsql@latestbun add mastra@latest @mastra/core@latest @mastra/libsql@latestTo integrate Mastra into your project, you have two options:
-
Use the One-Liner
Run the following command to quickly scaffold the default Weather agent with sensible defaults:
npx mastra@latest init --defaultSee mastra init for more information.
-
Use the Interactive CLI
If you prefer to customize the setup, run the
initcommand and choose from the options when prompted:npx mastra@latest init
Add the
devandbuildscripts topackage.json:package.json{
"scripts": {
...
"dev:mastra": "mastra dev",
"build:mastra": "mastra build"
}
}-
Modify the
tsconfig.jsonfile in your project root:tsconfig.json{
...
"exclude": ["dist", ".mastra"]
}The
VITE_prefix is required for environment variables to be accessible in the Vite environment, that SvelteKit uses. Read more about Vite environment variables..envVITE_OPENAI_API_KEY=<your-api-key>Add
.mastrato your.gitignorefile:.gitignore.mastraUpdate the Mastra Agent
src/mastra/agents/weather-agent.ts- import { openai } from "@ai-sdk/openai";
+ import { createOpenAI } from "@ai-sdk/openai";
+ const openai = createOpenAI({
+ apiKey: import.meta.env?.VITE_OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY,
+ compatibility: "strict"
+ });By reading env vars from both
import.meta.envandprocess.env, we ensure that the API key is available in both the SvelteKit dev server and the Mastra Dev Server.More configuration details are available in the AI SDK docs. See Provider Instance for more information.
Start the Mastra Dev Server to expose your agents as REST endpoints:
- npm
- CLI
npm run dev:mastramastra dev:mastraOnce running, your agents are available locally. See Local Development Environment for more information.
With the Mastra Dev Server running, you can start your SvelteKit site in the usual way.
mkdir src/routes/testCreate a new Action, and add the example code:
touch src/routes/test/+page.server.tssrc/routes/test/+page.server.tsimport type { Actions } from "./$types";
import { mastra } from "../../mastra";
export const actions = {
default: async (event) => {
const city = (await event.request.formData()).get("city")!.toString();
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate(`What's the weather like in ${city}?`);
return { result: result.text };
},
} satisfies Actions;Create a new Page file, and add the example code:
touch src/routes/test/+page.sveltesrc/routes/test/+page.svelte<script lang="ts">
import type { PageProps} from './$types';
let { form }: PageProps = $props();
</script>
<h1>Test</h1>
<form method="POST">
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{#if form?.result}
<pre>{form.result}</pre>
{/if}You can now navigate to
/testin your browser to try it out.Submitting London as the city would return a result similar to:
The current weather in London is as follows:
- **Temperature:** 16°C (feels like 13.8°C)
- **Humidity:** 62%
- **Wind Speed:** 12.6 km/h
- **Wind Gusts:** 32.4 km/h
- **Conditions:** Overcast
If you need more details or information about a different location, feel free to ask!
Install the required Mastra packages:
- npm
- yarn
- pnpm
- bun
npm install mastra@latest @mastra/core@latest @mastra/libsql@latestyarn add mastra@latest @mastra/core@latest @mastra/libsql@latestpnpm add mastra@latest @mastra/core@latest @mastra/libsql@latestbun add mastra@latest @mastra/core@latest @mastra/libsql@latestTo integrate Mastra into your project, you have two options:
-
Use the One-Liner
Run the following command to quickly scaffold the default Weather agent with sensible defaults:
npx mastra@latest init --defaultSee mastra init for more information.
-
Use the Interactive CLI
If you prefer to customize the setup, run the
initcommand and choose from the options when prompted:npx mastra@latest init
Add the
devandbuildscripts topackage.json:package.json{
"scripts": {
...
"dev:mastra": "mastra dev",
"build:mastra": "mastra build"
}
}-
Modify the
tsconfig.jsonfile in your project root:tsconfig.json{
...
"exclude": ["dist", ".mastra"]
}The
VITE_prefix is required for environment variables to be accessible in the Vite environment, that SvelteKit uses. Read more about Vite environment variables..envVITE_OPENAI_API_KEY=<your-api-key>Add
.mastrato your.gitignorefile:.gitignore.mastraUpdate the Mastra Agent
src/mastra/agents/weather-agent.ts- import { openai } from "@ai-sdk/openai";
+ import { createOpenAI } from "@ai-sdk/openai";
+ const openai = createOpenAI({
+ apiKey: import.meta.env?.VITE_OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY,
+ compatibility: "strict"
+ });By reading env vars from both
import.meta.envandprocess.env, we ensure that the API key is available in both the SvelteKit dev server and the Mastra Dev Server.More configuration details are available in the AI SDK docs. See Provider Instance for more information.
Start the Mastra Dev Server to expose your agents as REST endpoints:
- npm
- CLI
npm run dev:mastramastra dev:mastraOnce running, your agents are available locally. See Local Development Environment for more information.
With the Mastra Dev Server running, you can start your SvelteKit site in the usual way.
mkdir src/routes/weather-apiCreate a new Endpoint, and add the example code:
touch src/routes/weather-api/+server.tssrc/routes/weather-api/+server.tsimport { json } from "@sveltejs/kit";
import { mastra } from "../../mastra";
export async function POST({ request }) {
const { city } = await request.json();
const response = await mastra
.getAgent("weatherAgent")
.generate(`What's the weather like in ${city}?`);
return json({ result: response.text });
}Create a new Page, and add the example code:
touch src/routes/weather-api-test/+page.sveltesrc/routes/weather-api-test/+page.svelte<script lang="ts">
let result = $state<string | null>(null);
async function handleFormSubmit(event: Event) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const city = formData.get('city')?.toString();
if (city) {
const response = await fetch('/weather-api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ city })
});
const data = await response.json();
result = data.result;
}
}
</script>
<h1>Test</h1>
<form method="POST" onsubmit={handleFormSubmit}>
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{#if result}
<pre>{result}</pre>
{/if}You can now navigate to
/weather-api-testin your browser to try it out.Submitting London as the city would return a result similar to:
The current weather in London is as follows:
- **Temperature:** 16.1°C (feels like 14.2°C)
- **Humidity:** 64%
- **Wind Speed:** 11.9 km/h
- **Wind Gusts:** 30.6 km/h
- **Conditions:** Overcast
If you need more details or information about a different location, feel free to ask!
## Next steps