More typing
When building robust APIs, TypeScript is your best friend! Dotpress gives you full control over the types of your application, from the request inputs to the handler output. Here's how to enhance type safety in two key areas: response types and authenticated user types.
Typing handler return
By default, handlers return unknown
but you can enforce the return type using generics on defineRoute.
type Guide = {
title: string;
href: string;
summary: string;
}
defineRoute<Guide>({
method: 'get',
path: '/guides/:slug',
handler: async () => {
return {
title: 'More Typing',
href: '/typing',
summary: 'Discover how to type your API handlers.'
}
}
});
In this way, you will get full autocompletion and type checking.
Typing authenticated user
Authenticating user is not in the scope of this package, but the handler context objet provides you with a user
property that you can use in your middlewares to handle authentication. By default, user is typed as unknown | undefined
. Here's how to properly type ctx.user
according to your data structure.
1. Extend AppTypes in your app
// types/dotpress.d.ts
import 'dotpress';
declare module 'dotpress' {
interface AppTypes {
user: {
id: string;
name: string;
email: string;
roles: string[];
isValidated: boolean;
};
}
}
2. Use context user in route handlers
defineRoute({
path: '/admin',
handler: async ({ user }) => {
// user is fully typed here
if (!user?.roles.includes('admin')) {
return { access: 'denied' };
}
return { access: 'granted' };
}
});
Notes:
- The typing is global and doesn’t require passing generics to every route.
- This typing only affects the developer experience — no runtime behavior is changed.