npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

strapi-client-nextjs

v1.0.2

Published

Next.js 14 client for Strapi Rest API using next/cache

Downloads

84

Readme

strapi-client-nextjs

This is a fork of strapi-client-nextjs, with caching for nextjs using next/cache.

Installation

npm i strapi-client-nextjs axios qs

 or

yarn add strapi-client-nextjs axios qs

Peer Dependencies

This package uses axios as a http client and qs for parsing and stringifying the query.

Create Client Options

// Typescript

import { createClient, StrapiClientOptions } from 'strapi-client-nextjs';

const options: StrapiClientOptions = {
  url: 'http://localhost:1337/api',
  apiToken: '', // Built in API token,
  normalizeData: true, // Normalize Unified response Format. default - true
  headers: {}, // Custom Headers
  persistSession: false, // Persist authenticated token in browser local storage. default -false
  tags: [] // revalidation tags for nextjs
  revalidate: 0 // revalidation timeout for nextjs
};

const strapiClient = createClient(options);

REST API

Get

import { createClient } from 'strapi-client-nextjs';

const strapiClient = createClient({ url: 'http://localhost:1337/api' });

const run = async () => {
  const { data, error, meta } = await strapiClient
    .from('students')
    // .from<Student>("students") ** typescript **
    .select(['firstname', 'lastname']) // Select only specific fields.
    // .select(["firstname", "lastname"]) ** typescript **
    .get();

  if (error) {
    console.log(error);
  } else {
    console.log(data);
    console.log(meta);
  }
};

run();

Retrieve many entries by ids

const { data, error, meta } = await strapiClient.from('students').selectManyByID([200, 240]).get();

Adding next/cache tags

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select()
  .setTags(['refresh'])
  .get();

Filter Methods

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .equalTo('id', 2)
  .get();
const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .between('id', [40, 45])
  .get();

All filter Methods

equalTo();
notEqualTo();
lessThan();
lessThanOrEqualTo();
greaterThan();
greaterThanOrEqualTo();
containsCaseSensitive();
notContainsCaseSensitive();
contains();
notContains();
isNull();
isNotNull();
between();
startsWith();
endsWith();

Filter Deep

@param path - as string by relation @param Operator "eq" | "ne" | "lt" | "gt" | "lte" | "gte" | "in" | "notIn" | "contains" | "notContains" | "startsWith" | "endsWith" @param values can be string, number or array

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .filterDeep('address.city', 'eq', 'Munich')
  .get();

Sort

Expects an array with the field and order example - [{ field: 'id', order: 'asc' }]

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .between('id', [40, 45])
  .sortBy([{ field: 'id', order: 'desc' }])
  .get();

Publication State

Returns both draft entries & published entries.

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .withDraft()
  .get();

Returns only draft entries.

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .onlyDraft()
  .get();

Locale

Get entries from a specific locale.

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .setLocale('de')
  .get();

Pagination

To paginate results by page

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .paginate(1, 15)
  .get();

To paginate results by offset

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .paginateByOffset(0, 25)
  .get();

Populate

Populate 1 level for all relations

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .populate()
  .get();

Populate 2 levels

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .populateWith<Address>('address', ['id', 'city'], true)
  .get();

Populate Deep

const { data, error, meta } = await strapiClient
  .from<Student>('students')
  .select(['firstname', 'lastname'])
  .populateDeep([
    {
      path: 'address',
      fields: ['id', 'string'],
      children: [{ key: 'country', fields: ['id', 'name'] }],
    },
  ])
  .get();

Post

Create single record

const { data, error, meta } = await strapiClient
  .from('students')
  .create({ firstname: 'Vorname', lastname: 'Nachname' });

Create Many records

const { success } = await strapiClient.from('students').createMany([
  { firstname: 'muster', lastname: 'muster' },
  { firstname: 'muster1', lastname: 'muster1' },
]);

Available Post Methods

update();
updateMany();
deleteOne();
deleteMany();

Auth

signup new user

  const { data, error } = await strapiClient.auth.signUp({
    username: 'username',
    email: '[email protected]',
    password: '12345678',
  });

signin user

  const { data, error } = await strapiClient.auth.signIn({
    email: '[email protected]',
    password: '12345678',
  });

signout user - removes the authentication token if saved in localstorage

  const { error } = await strapiClient.auth.signOut();

Misc

Get url from the client Object

  const url = strapiClient.getApiUrl();

  console.log(url);

Set up revalidation on Strapi

  1. Create an API route in your frontend with the following code:
import { revalidateTag } from "next/cache";
import { NextRequest } from "next/server";

export async function POST(request: NextRequest) {
  const body = await request.json();
  const strapiTag = body.model;

  revalidateTag(strapiTag);

  console.log(`Revalidated ${strapiTag}`);
  return Response.json({ revalidated: strapiTag, now: Date.now() });
}
  1. Set up a webhook in Strapi settings with the API endpoint on the frontend and enable the relevant events.
  2. Add plural and singular endpoints as tags in the strapi client requests using the .setTags() method.