Creating a small layer to communicate to your API:
// api/usersimport { mande } from 'mande'const users = mande('/api/users', globalOptions)export function getUserById(id) { return users.get(id)}export function createUser(userData) { return users.post(userData)}
Adding Authorization tokens:
// api/usersimport { mande } from 'mande'const todos = mande('/api/todos', globalOptions)export function setToken(token) { // todos.options will be used for all requests todos.options.headers.Authorization = 'Bearer ' + token}export function clearToken() { delete todos.options.headers.Authorization}export function createTodo(todoData) { return todo.post(todoData)}
// In a different file, setting the token whenever the login status changes. This depends on your frontend code, for instance, some libraries like Firebase provide this kind of callback but you could use a watcher on Vue.onAuthChange((user) => { if (user) setToken(user.token) else clearToken()})
You can also globally add default options to all mande instances:
import { defaults } from 'mande'defaults.headers.Authorization = 'Bearer token'
TypeScript
All methods defined on a mande instance accept a type generic to type their return:
const todos = mande('/api/todos', globalOptions)todos .get<{ text: string; id: number; isFinished: boolean }[]>() .then((todos) => { // todos is correctly typed })
SSR (and Nuxt in Universal mode)
To make Mande work on Server, make sure to provide a fetch polyfill and to use full URLs and not absolute URLs starting with /. For example, using node-fetch, you can do:
export const BASE_URL = process.server ? process.env.NODE_ENV !== 'production' ? 'http://localhost:3000' : 'https://example.com' : // on client, do not add the domain, so urls end up like `/api/something` ''const fetchPolyfill = process.server ? require('node-fetch') : fetchconst contents = mande(BASE_URL + '/api', {}, fetchPolyfill)
Nuxt 2
Note: If you are doing SSR with authentication, Nuxt 3 hasn't been adapted yet. See #308.
When using with Nuxt and SSR, you must wrap exported functions so they automatically proxy cookies and headers on the server: