External logic with interceptors
While some headers might be applicable to only one endpoint, most often, we want to be able to apply the same logic across different endpoints. In the case of the auth_token
header, if we have multiple routes that can only be called when the user is logged in, we do not want to repeat all the checks we did in the previous section. It bloats the code; it is not maintainable; and it might distract developers when finding the heart of the endpoint. This is why we will use an authentication interceptor. We will extract that authentication logic and it will be called before each call in the API.
Our interceptors will be called authInterceptor
. The interceptor on the server side will simply do all the checks we did in the previous section, and then if everything goes well, the execution of the endpoint will be launched. Otherwise, the interceptor will return the error and the endpoint will not be called.
To define a server side interceptor, we have...