Svelte and SvelteKit course ยท Module 13: Form Actions

The Market of Birka - Form Actions

2 min read ยท
In this lesson3

Welcome to the market in Birka! Here Vikings trade and make deals. Form Actions in SvelteKit are the way to handle forms on the server side.

Basic form

<!-- src/routes/warriors/new/+page.svelte -->
<form method="POST">
  <input name="name" placeholder="Warrior name" required />
  <input name="strength" type="number" placeholder="Strength" required />
  <button type="submit">Add warrior</button>
</form>
// src/routes/warriors/new/+page.server.js
export const actions = {
  default: async ({ request }) => {
    const data = await request.formData();
    const name = data.get('name');
    const strength = data.get('strength');

    // Save to database
    await db.warriors.create({ name, strength: Number(strength) });

    return { success: true };
  }
};

Named actions

// +page.server.js
export const actions = {
  create: async ({ request }) => {
    // ...
  },
  delete: async ({ request }) => {
    // ...
  }
};
<form method="POST" action="?/create">
  <!-- ... -->
</form>

<form method="POST" action="?/delete">
  <input type="hidden" name="id" value={warrior.id} />
  <button>Delete</button>
</form>

Returning data

Whatever the action returns reaches the page as the form prop. In Svelte 5 you receive it with $props(), together with data if the page needs it: let { data, form } = $props();.

<script>
  let { form } = $props();
</script>

{#if form?.success}
  <p class="success">Warrior added!</p>
{/if}

{#if form?.error}
  <p class="error">{form.error}</p>
{/if}

<form method="POST">
  <!-- ... -->
</form>

The market requires negotiation - forms require validation!

Code for this lesson: App.svelte
<script>
  // Birka Market - Form Actions
  // Forms without client-side JavaScript

  let warriors = $state([
    { id: 1, name: 'Ragnar', strength: 95 },
    { id: 2, name: 'Bjorn', strength: 90 }
  ]);

  let formData = $state({ name: '', strength: 50 });
  let message = $state('');

  // Simulating form action
  function handleSubmit(e) {
    e.preventDefault();

    if (!formData.name) {
      message = 'Name is required!';
      return;
    }

    warriors = [...warriors, {
      id: Date.now(),
      name: formData.name,
      strength: formData.strength
    }];

    formData = { name: '', strength: 50 };
    message = 'Warrior added!';

    setTimeout(() => message = '', 2000);
  }
</script>

<main class="birka">
  <h1>Birka Market - Form Actions</h1>
  <p class="subtitle">Forms in SvelteKit</p>

  <section class="code">
    <h2>+page.server.js</h2>
    <pre>
export const actions = {"{"}
  default: async ({"{"} request {"}"}) => {"{"}
    const data = await request.formData();
    const name = data.get('name');

    // Validation
    if (!name) {"{"}
      return fail(400, {"{"} error: 'Name required' {"}"});
    {"}"}

    // Save to database
    await db.warriors.create({"{"} name {"}"});

    return {"{"} success: true {"}"};
  {"}"}
{"}"};
    </pre>
  </section>

  <section class="form-section">
    <h2>Add warrior</h2>

    <!-- In SvelteKit: method="POST" is enough -->
    <form onsubmit={handleSubmit}>
      <div class="field">
        <label for="name">Warrior name</label>
        <input
          id="name"
          name="name"
          bind:value={formData.name}
          placeholder="np. Ivar"
        />
      </div>

      <div class="field">
        <label for="strength">Strength ({formData.strength})</label>
        <input
          type="range"
          id="strength"
          name="strength"
          bind:value={formData.strength}
          min="1"
          max="100"
        />
      </div>

      <button type="submit">Add warrior</button>
    </form>

    {#if message}
      <p class="message">{message}</p>
    {/if}
  </section>

  <section class="list">
    <h2>Warriors ({warriors.length})</h2>
    {#each warriors as warrior (warrior.id)}
      <div class="warrior">
        <span>{warrior.name}</span>
        <span class="strength">{warrior.strength}</span>
      </div>
    {/each}
  </section>
</main>

<style>
  .birka {
    font-family: 'Georgia', serif;
    max-width: 500px;
    margin: 0 auto;
    padding: 2rem;
    background: #1a0f0a;
    color: #e8d5b7;
    min-height: 100vh;
  }

  h1 {
    color: #d4af37;
    text-align: center;
  }

  .subtitle {
    text-align: center;
    color: #8b7355;
  }

  section {
    background: rgba(212, 175, 55, 0.1);
    border: 1px solid #d4af37;
    border-radius: 8px;
    padding: 1rem;
    margin: 1rem 0;
  }

  h2 {
    color: #d4af37;
    font-size: 1rem;
    margin-top: 0;
  }

  pre {
    background: rgba(0,0,0,0.5);
    padding: 1rem;
    border-radius: 4px;
    font-size: 0.8rem;
    overflow-x: auto;
  }

  .field {
    margin-bottom: 1rem;
  }

  label {
    display: block;
    margin-bottom: 0.25rem;
    color: #d4af37;
  }

  input[type="text"],
  input[name="name"] {
    width: 100%;
    padding: 0.75rem;
    background: rgba(0,0,0,0.3);
    border: 1px solid #3d2914;
    border-radius: 4px;
    color: #e8d5b7;
  }

  input[type="range"] {
    width: 100%;
  }

  button {
    width: 100%;
    padding: 0.75rem;
    background: #3d2914;
    color: #e8d5b7;
    border: 1px solid #d4af37;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
  }

  button:hover {
    background: #4d3924;
  }

  .message {
    margin-top: 1rem;
    padding: 0.75rem;
    background: rgba(144, 238, 144, 0.1);
    border-radius: 4px;
    text-align: center;
  }

  .warrior {
    display: flex;
    justify-content: space-between;
    padding: 0.75rem;
    background: rgba(0,0,0,0.3);
    border-radius: 4px;
    margin-bottom: 0.5rem;
  }

  .strength {
    color: #ffd700;
  }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Where do we define form actions in SvelteKit?

Hands-on tasks in the game

  • Code editor

    Complete the form's action attribute

  1. QuestionWhere Form Actions Live
  2. Coding taskPractice: A Form with the create Action

Useful articles