Vanilla JS and Other Frameworks
Vanilla JS and Other Frameworks
The core client has no framework dependencies, so it works anywhere modern fetch is available: Node 18+, browsers, edge runtimes, Astro, SvelteKit, and so on.
Vanilla JS with manual DOM
<div id="blog"></div>
<script type="module">
import { createClient } from 'https://esm.sh/@rankhiker/sdk';
const rh = createClient({
apiKey: 'rh_export_...',
baseUrl: 'https://rankhiker.com',
});
const posts = await rh.listArticles({ limit: 10 });
const root = document.getElementById('blog');
root.innerHTML = posts
.map(
(post) => `
<article>
<a href="/blog/${post.slug}">
<h2>${post.title}</h2>
<p>${post.excerpt}</p>
</a>
</article>`,
)
.join('');
</script>
To render a full article, fetch by slug and inject its HTML body:
const post = await rh.getArticleBySlug('my-slug');
if (post) {
document.getElementById('post').innerHTML = post.content;
}
ESM import
import { createClient } from '@rankhiker/sdk';
const rh = createClient({ apiKey: process.env.RANKHIKER_API_KEY });
const posts = await rh.listArticles();
CommonJS require
const { createClient } = require('@rankhiker/sdk');
const rh = createClient({ apiKey: process.env.RANKHIKER_API_KEY });
rh.listArticles().then((posts) => console.log(posts.length));
Astro (server-side frontmatter)
Astro frontmatter runs on the server, so the key stays private and there is no redirect concern.
---
import { createClient } from '@rankhiker/sdk';
const rh = createClient({ apiKey: import.meta.env.RANKHIKER_API_KEY });
const posts = await rh.listArticles({ limit: 12 });
<ul>
{posts.map((post) => (
<li><a href={/blog/${post.slug}}>{post.title}</a></li>
))}
</ul>
A single Astro article page:
---
import { createClient } from '@rankhiker/sdk';
const rh = createClient({ apiKey: import.meta.env.RANKHIKER_API_KEY });
const { slug } = Astro.params;
const post = await rh.getArticleBySlug(slug);
if (!post) return Astro.redirect('/404');
<article>
<h1>{post.title}</h1>
<Fragment set:html={post.content} />
</article>
Error handling anywhere
The same RankHikerError is thrown in every environment. Browser code can hit a 401 when the API key header is dropped across a redirect, so use the default apex baseUrl (https://rankhiker.com) and avoid the www host.
import { createClient, RankHikerError } from '@rankhiker/sdk';
const rh = createClient({ apiKey: '...', baseUrl: 'https://rankhiker.com' });
try {
const posts = await rh.listArticles();
} catch (err) {
if (err instanceof RankHikerError) {
console.error('status', err.status, 'at', err.endpoint);
}
}
Was this article helpful?