Git Product home page Git Product logo

next's Introduction

Add authentication and monetization to your React application in minutes using Kobble

License Status

Add authentication, monetization and permissions to your Next.js application in minutes using Kobble Next SDK.

It's secure by design and easy to use.

Getting Started

Installation

Using npm in your project directory run the following command:

npm install @kobbleio/next

# or
pnpm install @kobbleio/next

Configure Kobble

Create an Application in your Kobble Dashboard.

Make sure your application can handle your localhost callback URL (see section below).

Note the Client ID and your Portal Domain values.

Visit our Quick Start Guide to learn more.

Working with the app router

This SDK only supports the app router which is available since Next.js 13 and is now considered to be Next's default router.

  • @kobbleio/next/server => utilities to work on the server side (usable in server side components and route handlers)
  • @kobbleio/next/client => utilities to work on the client side (browser)
  • @kobbleio/next => utilities that can safely be used on both sides

Setup the middleware

Create a middleware.ts file in your project and add the following code:

import { authMiddleware } from '@kobbleio/next/server'

export default authMiddleware({
	publicRoutes: ['/'],
});

export const config = {
  matcher: [
    // exclude internal Next.js routes
    "/((?!.+\\.[\\w]+$|_next).*)",
    // reinclude api routes
    "/(api|trpc)(.*)"
  ]
};

This middleware will automatically expose various routes to handle authentication.

Setup client side provider

To leverage kobble utilities inside client side components, you need to wrap your app with the KobbleProvider component. This is commonly done in the top level layout.tsx file as shown below:

import { KobbleProvider } from "@kobbleio/next/server";

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
	  	<KobbleProvider>
	  		{children}
		</KobbleProvider>
	  </body>
    </html>
  );
}

Note that KobbleProvider itself is a server side component, and as such should not be rendered by a client component directly.

Basic usage

Only basic usage is documented here. For an exhaustive list of available functions, please check the official documentation.

Access user session on the server

You can access the user session on the server by calling the getAuth function from @kobbleio/next/server:

import { getAuth } from '@kobbleio/next/server'

export default async function handler(req, res) {
  const { session } = await getAuth();

  if (!session) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // An active session was found. User and tokens can be accessed from the session object. 
  // <further logic here...>
}

Access user session on the client

You can access the user session on the client by calling the useAuth hook from @kobbleio/next/client:

Note that useAuth will first have to fetch the user session from the server, so you need to check for the loading state to know when the session information (if any) is available.

If your use case allows it, it is recommended to fetch the session on the server instead and pass it to the client side as a prop.

import { useAuth } from '@kobbleio/next/client'

export default function ExampleProfile() {
  const { user, isLoading } = useAuth();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (!user) {
    return <div>Not authenticated</div>;
  }

  return <div>Hello, {user.email}</div>;
}

Use kobble client SDK

You can use the lower level client SDK Kobble by calling getKobble if on the server, or useKobble if on the client:

import { getKobble } from '@kobbleio/next/server'

export default async function handler(req, res) {
  const kobble = await getKobble();

  // Use the kobble SDK here
}
import { useKobble } from '@kobbleio/next/client'

export default function ExampleComponent() {
  const { kobble } = useKobble();

  // Use the kobble SDK here
}

The usage is exactly the same whether you are on the server or on the client.

A working client SDK is always returned, even if the user is not authenticated. In such scenario though, most functions will throw an error if called. It is your responsability to make sure the user is authenticated before calling any function that requires it.

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.


What is Kobble?

Kobble Logo

Kobble is the one-stop solution for monetizing modern SaaS. It allows to add authentication, monetization and permissions to any modern app in under 10 minutes.

next's People

Contributors

aurelien-brabant avatar kevinpiac avatar theshinriel avatar

Stargazers

Valensto avatar

Watchers

 avatar

Forkers

theshinriel

next's Issues

next@rc broken

Hello, when using next@rc kobble breaks, you might want to know that:
From kobble-next-examples/simple-auth-example

❯ bun dev
$ next dev
✔ Console Ninja extension is connected to Next.js, see https://tinyurl.com/2vt8jxzw
  ▲ Next.js 14.2.4
  - Local:        http://localhost:3000
  - Environments: .env

 ✓ Starting...
 ✓ Ready in 2.1s
 ○ Compiling /src/middleware ...
 ✓ Compiled /src/middleware in 554ms (125 modules)
 ○ Compiling / ...
 ✓ Compiled / in 2.8s (620 modules)
 GET /?code=dfa2818b95d715acdef2823141f258a39b16f16b321f10270c5dd09e06a3b463&state=kobble 200 in 3122ms
 ✓ Compiled in 309ms (276 modules)
 GET /?code=dfa2818b95d715acdef2823141f258a39b16f16b321f10270c5dd09e06a3b463&state=kobble 200 in 44ms
 ○ Compiling /favicon.ico ...
 ✓ Compiled /favicon.ico in 2.6s (364 modules)
 GET /favicon.ico 200 in 2761ms
 GET /?code=dfa2818b95d715acdef2823141f258a39b16f16b321f10270c5dd09e06a3b463&state=kobble 200 in 1464ms
 GET /?code=dfa2818b95d715acdef2823141f258a39b16f16b321f10270c5dd09e06a3b463&state=kobble 200 in 36ms
 GET /favicon.ico 200 in 10ms
 GET /?code=dfa2818b95d715acdef2823141f258a39b16f16b321f10270c5dd09e06a3b463&state=kobble 200 in 12ms
 GET /favicon.ico 200 in 13ms
^C
❯ bun add next@rc
[0.01ms] ".env"
bun add v1.1.10 (5102a944)
warn: incorrect peer dependency "[email protected]"

warn: incorrect peer dependency "[email protected]"

installed [email protected] with binaries:
 - next

21 packages installed [1.94s]

Now its broken

❯ bun dev
$ next dev
✔ Console Ninja extension is connected to Next.js, see https://tinyurl.com/2vt8jxzw
 ⚠ Port 3000 is in use, trying 3001 instead.
  ▲ Next.js 15.0.0-rc.0
  - Local:        http://localhost:3001
  - Environments: .env

 ✓ Starting...

   We detected TypeScript in your project and reconfigured your tsconfig.json file for you.
   The following suggested values were added to your tsconfig.json. These values can be changed to fit your project's needs:

   	- target was set to ES2017 (For top-level `await`. Note: Next.js only polyfills for the esmodules target.)

 ⚠ Found lockfile missing swc dependencies, patching...
 ⨯ Failed to patch lockfile, please try uninstalling and reinstalling next in this workspace
TypeError: Cannot read properties of undefined (reading 'os')
    at fetchPkgInfo (/home/adelin/Documents/Projects/phagos/test-kobble/kobble-next-examples/simple-auth-example/node_modules/next/dist/lib/patch-incorrect-lockfile.js:73:25)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Promise.all (index 0)
    at async patchIncorrectLockfile (/home/adelin/Documents/Projects/phagos/test-kobble/kobble-next-examples/simple-auth-example/node_modules/next/dist/lib/patch-incorrect-lockfile.js:162:26)
 ✓ Ready in 1865ms
 ○ Compiling /src/middleware ...
 ✓ Compiled /src/middleware in 555ms (129 modules)
 ⨯ node_modules/@kobbleio/next/dist/client/context/auth/provider.js (7:8) @ <unknown>
 ⨯ (0 , _react.createContext) is not a function
   5 | import { routes } from "../../../constants";
   6 | import { createContext } from 'react';
>  7 | export const authContext = /*#__PURE__*/ createContext({
     |        ^
   8 |     user: null,
   9 |     logout: ()=>{},
  10 |     login: ()=>{},
 ○ Compiling /_error ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.