Skip to content

Instantly share code, notes, and snippets.

@ravenwilde
Created March 12, 2024 04:19
Show Gist options
  • Save ravenwilde/ccfa8aa59762d1e5905b41dd597e7a80 to your computer and use it in GitHub Desktop.
Save ravenwilde/ccfa8aa59762d1e5905b41dd597e7a80 to your computer and use it in GitHub Desktop.
JSON Web Token authentication functions for use with WPGraphQL JWT Authentication plugin
const API_URL = process.env.WORDPRESS_API_URL
/**
* Fetches the API to get the JWT refresh token
* @returns {Promise<string>} The JWT refresh token
*/
export async function fetchToken() {
const query = `
mutation LoginUser($input: LoginInput!) {
login(input: $input) {
authToken
user {
id
name
}
}
}
`
const variables = { input: {
clientMutationId: v4(),
username: process.env.WORDPRESS_USERNAME,
password: process.env.WORDPRESS_PASSWORD,
}
}
const res = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.data.login) {
return json.data.login.authToken
} else {
throw new Error(`Failed to fetch API token`)
}
}
async function fetchAPI(query = '', { variables }: Record<string, any> = {}) {
const headers = { 'Content-Type': 'application/json' }
const token = await fetchToken();
if (token) {
headers[
'Authorization'
] = `Bearer ${token}`
}
// WPGraphQL Plugin must be enabled
const res = await fetch(API_URL, {
headers,
method: 'POST',
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment