next-pocketbase-auth
Version:
Wrapper for Next.js applications using PocketBase, with support for both client and server components
2 lines (1 loc) • 1.8 kB
JavaScript
;var S=Object.defineProperty;var w=(t,e,r)=>e in t?S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var l=(t,e,r)=>w(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("js-cookie"),a=require("pocketbase"),f="http://127.0.0.1:8090/api/",s="pb_auth__",v={httpOnly:!1,secure:process.env.NODE_ENV==="production",sameSite:"strict",path:"/",expires:new Date(Date.now()+86400)};class d extends a.BaseAuthStore{constructor(r){super();l(this,"saveFunc");l(this,"clearFunc");if(this.saveFunc=r.save,this.clearFunc=r.clear,r.initial)try{const n=_(r.initial);this.save(n.token,n.record??n.model??null)}catch{}}save(r,n){super.save(r,n);let o="";const i={},u=a.getTokenPayload(r);"exp"in u&&typeof u.exp=="number"&&(i.expires=new Date(u.exp*1e3));try{o=O({token:r,record:n??null})}catch{console.warn("SyncAuthStore: failed to stringify the new state")}this.saveFunc(o,i)}clear(){this.clearFunc(),super.clear()}}function _(t){const e=JSON.parse(atob(t));if(typeof e=="object"&&e!==null&&"token"in e&&typeof e.token=="string"&&("record"in e||"model"in e))return e;throw new Error("Invalid DTO")}function O(t){return btoa(JSON.stringify(t))}function y(t){const e={...v,...t};return new d({save:(r,n)=>{p.set(s,r,{...e,...n})},clear:()=>{p.remove(s)},initial:p.get(s)})}let c;function b(t=process.env.NEXT_PUBLIC_PB_URL??f,e,r){return c||(c=new a(t,y(r),e),c)}function C(t,e){var n;const r={...v,...e};return new d({save:(o,i)=>{h(()=>t.set(s,o,{...r,...i}))},clear:()=>{h(()=>t.delete(s))},initial:(n=t.get(s))==null?void 0:n.value})}function h(t){try{t()}catch{}}function E(t,e=process.env.NEXT_PUBLIC_PB_URL??f,r,n){return new a(e,C(t,n),r)}exports.clientAuthStore=y;exports.createBrowserClient=b;exports.createServerClient=E;