This is the missing SvelteKit server functions library. (Well, sort of, it's more of a proof of concept. Not production ready.)
A SvelteKit preprocessor that automatically transforms server-side functions into API endpoints, enabling seamless client-server communication in your SvelteKit applications.
async function server_getData(id) {
// This code runs on the server
const data = await db.query('SELECT FROM items WHERE id = ?', [id]);
return data;
}
// Use the function as if it were local
const data = await server_getData(123);
npm install sveltekit-server-functions
svelte.config.js
:import serverFunctions from 'sveltekit-server-functions';
export default {
preprocess: [serverFunctions(), vitePreprocess()]
};
server_
:async function server_getData(id) {
// This code runs on the server
const data = await db.query('SELECT FROM items WHERE id = ?', [id]);
return data;
}
// Use the function as if it were local
const data = await server_getData(123);
The preprocessor will automatically:
server_
src/routes/api
directoryserver_
<script>
import { db } from '$lib/database';
// Define a server function to create a user
async function server_createUser(username, email) {
// This function runs on the server
const user = await db.users.create({
username,
email,
createdAt: new Date()
});
return user; // Return the created user
}
// Handle form submission
async function handleSubmit() {
try {
// Call the server function as if it were local
const newUser = await server_createUser('john_doe', '[email protected]');
console.log('User created:', newUser);
} catch (error) {
console.error('Failed to create user:', error);
}
}
</script>
<!-- Button to trigger user creation -->
<button on:click={handleSubmit}>Create User</button>
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - feel free to use this package in your projects!