Skip to content
Discussion options

You must be logged in to vote

you cant add custom options to Options without affecting all instances globally. instead, create a wrapper function with your custom options:

type CustomOptions = {
	withAuth?: boolean;
	unauthorizedCheck?: boolean;
};

function createApi(customOptions: CustomOptions = {}) {
	return ky.extend({
		hooks: {
			beforeRequest: [
				request => {
					if (customOptions.withAuth) {
						request.headers.set('Authorization', getToken());
					}
				}
			],
			afterResponse: [
				async (request, options, response) => {
					if (customOptions.unauthorizedCheck && response.status === 401) {
						// handle unauthorized
					}
				}
			]
		}
	});
}

// usage
const api = createApi({withAuth: true, u…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by sindresorhus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants