Middlewares
Middlewares are a powerful feature of tRPC that allow you to modify the request and response of an API endpoint. This can be useful for things like authentication, logging, error handling, and more.
Provided middlewares
SveltePak comes with a number of built-in middlewares that you can use out of the box. These include:
auth
- A middleware that checks if the user is authenticated and returns an error if not.role
- A middleware that checks if the user has the required role and returns an error if not.logger
- A middleware that logs the request and response to the console.
These middlewares are designed to be easy to use and customize, and can be used as a starting point for building your own middlewares.
Creating a middleware
To create a middleware, you can use the createMiddleware
function from tRPC. This function takes a handler function as an argument, which is called with the request and response objects. You can then modify these objects as needed and return the response.
Here’s an example of a simple middleware that logs the request and response:
import { t } from "$trpc/t";
export const logger = t.middleware(async ({ path, type, next }) => {
const start = Date.now();
const result = await next();
const ms = Date.now() - start;
console.log(`${result.ok ? "OK" : "ERR"} ${type} ${path} - ${ms}ms`);
return result;
});
In this example, we create a middleware called logger
that logs the request and response to the console. We use the next
function to call the next middleware in the chain, and then log the result and the time it took to process the request.
Using a middleware
Once you’ve created a middleware, you can use it in your API by adding it to the middlewares
array in the createRouter
function. For example:
import { auth } from "../middleware/auth";
export const invites = t.router({
validate: t.procedure.use(auth).query(async ({ input }) => {
// ...
})
});
In this example, we use the auth
middleware to protect the invites
endpoint. This means that the auth
middleware will be called before the invites
endpoint is executed, and will return an error if the user is not authenticated.
Middleware order
The order in which middlewares are added to the router is important. Middlewares are called in the order they are added, so you should be careful about the order in which you add them. For example, if you have a middleware that checks for authentication, you should add it before any other middlewares that depend on the user being authenticated.
Conclusion
Middlewares are a powerful feature of tRPC that allow you to modify the request and response of an API endpoint. They can be used for a wide variety of purposes, including authentication, logging, error handling, and more. By using middlewares, you can create a flexible and extensible API that can be easily customized to suit your needs.