Skip to content

deep_set crashes when setting a nested property on an existing key with value undefined or null #15599

@AndreasHald

Description

@AndreasHald

Describe the bug

deep_set in form-utils.js throws TypeError: Cannot set properties of undefined when attempting to set a value at a nested path where an intermediate key exists on the object but has a value of undefined or null.

This happens because deep_set uses Object.hasOwn(current, key) to decide whether to auto-create an intermediate container. When a key exists but holds undefined, hasOwn returns true, so auto-creation is skipped. The function then does current = current[key] (which becomes undefined), and the next iteration tries to assign a property on undefined, which throws.

Reproduction

import { deep_set } from '@sveltejs/kit/src/runtime/form-utils.js';

const obj = { nested: undefined };

// This throws: TypeError: Cannot set properties of undefined (setting 'name')
deep_set(obj, ['nested', 'name'], 'hello');

Expected: deep_set auto-creates the intermediate object, resulting in { nested: { name: 'hello' } } — the same behavior as when the key is completely absent.

Actual: TypeError: Cannot set properties of undefined (setting 'name')

Real-world scenario

This can happen with RemoteForm when using optional nested objects in a Zod schema:

const schema = z.object({
    name: z.string(),
    foo: z.record(z.string(), z.string()).optional(),
});


form.fields.set({
   name: 'some-name',
   foo: undefined
});

// throws
form.fields.foo.bar.set('will fail')

Suggested fix

In deep_set (form-utils.js, line 517), also check whether the existing value is nullish:

- if (!exists) {
+ if (!exists || current[key] == null) {
    current[key] = is_array ? [] : {};
  }

Logs

System Info

System:
    OS: macOS 26.3.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 108.00 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 24.13.0 - /Users/hald/.nvm/versions/node/v24.13.0/bin/node
    npm: 11.6.2 - /Users/hald/.nvm/versions/node/v24.13.0/bin/npm
    pnpm: 10.31.0 - /Users/hald/.nvm/versions/node/v24.13.0/bin/pnpm
  Browsers:
    Chrome: 146.0.7680.154
    Edge: 146.0.3856.72
    Firefox: 137.0.2
    Safari: 26.3.1
  npmPackages:
    @sveltejs/adapter-vercel: ^6.3.3 => 6.3.3 
    @sveltejs/kit: ^2.55.0 => 2.55.0 
    @sveltejs/vite-plugin-svelte: ^6.1.1 => 6.2.1 
    svelte: ^5.54.0 => 5.54.0 
    vite: ^7.3.0 => 7.3.0

Severity

serious, but I can work around it

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions