Skip to content

Endpoint Middleware #3881

@puchesjr

Description

@puchesjr

Describe the problem

I would like to propose a better model for endpoints middleware rather than the global hooks.

Current state: Today, we only have what appears to be one (1) hook src/hooks.ts that is run every time SvelteKit receives a request.

Issue: While this is ok for general things such as checking for authentication with a pathname
e.g., check_auth if pathname.startsWith('/admin'). The handle becomes quite large and unwieldy to check each pathname, etc.

Describe the proposed solution

Proposal: Permit the creation of one (1) hook per Endpoint in addition to the globally defined hook.

// src/routes/user.hook.ts 
// This file can be used to perform a logic for this endpoint only

export async function handle({event, resolve}) {
  const {method, body} = event.request;

  // get to the page if GET request
  if (method === 'GET') return resolve(event);
  
  try {
    await validate(body)
    return resolve(event)
  } catch (error) {
    return Response(JSON.stringify(e), {status: 422})
  }
}

The sequence for Sveltekit hooks would be as follows

src/hooks.ts -> src/{endpoint}.hook.{ts/js} -> src/{endpoint}.{ts/js} -> src/{endpoint}.svelte

This would provide a nice global hook with the additional benefits of a hook per endpoint.

Alternatives considered

Current implementation is as follows and is a terrible experience.

export async function handle({event, resolve}) {
  const route = event.url.pathname
  const {method, body} = event.request;

  switch (route) {
    case '/users':
      if (method === 'GET') return resolve(event);
      try {
        await validateUserBody(body)
        return resolve(event)
      } catch (error) {
        return Response(JSON.stringify(e), {status: 422})
      }
      break;

    case '/notes':
      if (method === 'GET') return resolve(event);
      try {
        await validateNotesBody(body)
        return resolve(event)
      } catch (error) {
        return Response(JSON.stringify(e), {status: 422})
      }
      break;

    .... other endpoints....
  }
}


### Importance

would make my life easier

### Additional Information

I think this feature would be nice to have too many of the developers that are using Sveltekit today.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions