Skip to content

codiku-dev/next-auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Next Boiler Plate

Next.JS + Typescript + Next Auth + Tailwind + Shadcnui + Prisma + Supabase + Playwright + Storybook + React Query + Next Intl

⚡️ Unleash the power of Next Auth, Tailwind CSS, and Shadcnui to create stunning web experiences.

This comprehensive boilerplate provides a solid foundation for building modern web applications with the latest technologies. It features seamless user authentication, rapid styling with Tailwind CSS, data validation with Zod, toast and response management with axios-config, routes protection and validations with safeEndPoint(), CRUD generation shortcut, efficient database interaction with Prisma, and user interface enhancements with Shadcnui

🔥 Key Features:

  • 🛡 Next Auth for Seamless Authentication: Seamlessly manage user authentication, including login, registration, password resets, and email verification.

  • 🎨 Tailwind CSS for Blazing Speed and Consistency + Theming support : Leverage Tailwind CSS's utility-first approach + global theme stylesheets for rapid and consistent styling across all devices.

  • ✔️ Data Validation with Zod: Ensure data integrity and prevent errors with Zod, a powerful JSON schema validator.

  • 📢 Toast and Response Management with Axios-config: Easily display alerts and manage responses with axios-config.

  • 🚧 Routes Protection and Validations with safeEndPoint() hoc: Protect your routes and enforce data validations with the safeEndPoint() hoc.

  • ⚙️ CRUD Generation Shortcut with npm run crud: Quickly generate GET, POST, PATCH, and DELETE API routes and server action, based on Prisma schema.

  • 💾 Database Management with Prisma: Efficiently interact with your Postgres database with Prisma, an open-source ORM.

  • 🌟 User Interface Enhancements with Shadcnui: Enhance the user experience with Shadcnui, a react component library for building user interfaces.

  • 📚 Comprehensive Documentation with Swagger: Easily navigate and understand the API endpoints with Swagger documentation, ensuring a smooth integration process for developers.

  • 🧩 Interactive UI Components with Storybook: Utilize Storybook to build and test UI components in isolation, enhancing the development workflow and ensuring consistency across your application.

  • 🌍 Internationalization with Next Intl: Simplify the process of internationalizing your application with Next Intl, providing built-in support for translations, date, and number formatting.

Getting started

Install packages

npm i
```

Start the local db (if you want to use docker)

```shell
npm run db:start

Start the project

npm run db:migrate
npm run dev

Display the db

npm run db:studio

Toast and response

By default ky-config display alerts. Unless you send isToastDisabled:"false" in header request

Exemple :

const { mutate: resetPassword, isPending } = useMutation({
    mutationFn: async (data: { token: string; password: string }) =>
      api
        .patch("/api/auth/reset-password", {
          headers: { isToastDisabled: "true" },
          json: { token: data.token, password: data.password },
        })
        .json<Resp<{}>>(),
  });

Page protection

To makea page protected and redirect to sign in, add public routes to middleware.ts

exemple :

const publicPages = [
  "/",
  "/auth/signin",
  "/auth/signup",
  "/auth/forgot-password",
  "/auth/reset-password",
  "/sandbox",
];

API protection

Just wrap your handler with the safeEndPoint() hoc, This will allow you to send zod validator for query params, uri params and body. If the validation fails an error will be returned by the api.

The signature is the following :

export const PATCH = safeEndPoint(
  async (_req: NextRequest, { uriParams, queryParams, body }) => {
    const updatedProduct = await updateProduct({
      id: Number(route.params.id),
      ...body,
    });
    return NextResponse.json(updatedProduct);
  },
  {
    auth: true, // Is this end point public or private ?
    uriParams: PatchProductModelUriParams, // URI Params zod model
    queryParams: PatchProductModelQueryParams, // Query Params zod model
    bodyParams: PatchProductModelBody, // Body params zod model,
  }
);

Actions

Define a server action

export const updateProduct = safeAction(
  async ({ id, ...data }): Promise<Product> => {
    return db.product.update({
      where: { id },
      data,
    });
  },
  UpdateProductModelArgs
); // Pass here the zod schema for the server action

It handles validations for body and query params with typing

Calling Server actions component side

import { useAction } from "@/libs/use-action";

export default function SandboxPage() {
  // Action mutation
  const {
    isPending,
    execute: createProductMutation,
    data,
    error,
  } = useAction(createProduct);

  //action query
  const {
    isPending: isPendingReadProduct,
    execute: readProductMutation,
    data: readProductData,
  } = useAction(readProduct);
}

Session to access the auth user

To make sure you have access to the session, use withAuth and useSession hook

export default withAuth(function AccountPage() {
  const { data: session } = useSession();
  return <div>{session?.user?.email}</div>;
});

in Server side component you can also use

const serverSession = await getServerSession();

Generate a crud

npm run crud

will create GET,POST,PATCH,DELETE, a prisma schema, a zod prisma schema.

Swagger documentation

All Prisma and Zod models are automatically added to Swagger and can be used as JS Doc above the endpoint. Here is an example from route.ts:

Storybook

To run Storybook, use the following command:

npm run storybook

End to end testing with Playwright

To run Playwright tests, use the following command:

npm run test:e2e

Unit and Integration testing with testing-library

npm run test:unit

or

npm run test:integration

Theme

The theme-related styles are organized into several CSS files:

  • app/(pages)/theme-colors.css: Defines the color schemes used across the application.
  • app/(pages)/theme-globals.css: Sets up global styles that apply to all parts of the application.
  • app/(pages)/theme-components.css: Contains specific styles for components to ensure consistent design.

i18n translations

The format for the en.json is the name of the page then feature like this

Translation structure

 "Auth": {
    "account": {
      "title": "Account",
      ...
    },
    "forgot-password": {
      "title": "Forgot password",
      ...
    }
  }

Translate

You can use the getTranslations or useTranslations hook to get the translations. They receive the path to the translations as string.

In server side component

// Get all translations for the index page
const t = await getTranslations("Index");

In client side component

// Get only the translation for the forgot-password page
const t = useTranslations("Auth.forgot-password");

Github Actions

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published