GithubHelp home page GithubHelp logo

w3labkr / nextjs-ninja Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 1.0 3.2 MB

Nextjs-Ninja is a starter template for the NextJS 14 app router based on shadcn/ui.

Home Page: https://w3labkr-nextjs-with-supabase-auth.vercel.app

JavaScript 1.31% CSS 2.80% TypeScript 92.74% PLpgSQL 2.15% HTML 1.00%
nextjs react radix-ui shadcn-ui tailwindcss ts typescript javascript js i18next react-i18next supabase redux redux-persist redux-toolkit

nextjs-ninja's Introduction

NextJS with Supabase Auth

This is a starter template for the NextJS 14 app router with supabase auth based on shadcn-ui.

Denpendency

  • NextJS 14 + Typescript + Tailwind
  • Shadcn UI (Radix UI)
  • react-hook-form + zod
  • react-i18next + zod-i18n-map
  • Redux Toolkit + Redux Persist
  • Supabase OAuth with PKCE flow (@supabase/ssr)
  • Supabase Email Auth with PKCE flow (@supabase/ssr)
  • Supabase Role-based Access Control (RBAC)

The administrator page cannot be viewed on the demo page.
Check the files in the app/dashboard/admin directory.

Table of Contents

Screenshots

screenshot

Folder and file Structure

The folder and file structure is based on nextjs app router next.js project structure.

.
├── app/                        # App Router
│   └── api/
│       ├── auth/               # Public API for authentication
│       └── v1/                 # APIs that require authentication
├── components/                 # React components
├── config/                     # Configuration for site
├── context/
│   └── app-provider.ts         # Register context provider
├── hooks/
├── lib/                        # Utility functions
├── public/                     # Static assets to be served
│   └── [locales]/              # Internationalization
├── screenshots/                # Screenshots
├── sql/                        # Cloud functions
├── store/                      # Redux reducers
├── types/
├── components.json             # Shadcn UI
├── i18next.config.ts           # Internationalization
└── package.json                # Project dependencies and scripts

Installation

Prompts:

  • Would you like to use TypeScript? Yes
  • Would you like to use ESLint? Yes
  • Would you like to use Tailwind CSS? Yes
  • Would you like to use src/ directory? No
  • Would you like to use App Router? (recommended) Yes
  • Would you like to customize the default import alias (@/*)? No
  • What import alias would you like configured? @/*
npx create-next-app@latest . --typescript

React Hooks for Data Fetching

npm install swr

Set the current Node.js version.

node -v > .nvmrc

Start the development server.

npm run dev

Tailwind CSS

Install Tailwind CSS

npm install --save-dev tailwindcss postcss autoprefixer
npx tailwindcss init -p

Using 'clsx' or 'classnames' with 'tailwind-merge'

npm install tailwindcss-animate class-variance-authority clsx tailwind-merge

Tailwindcss plugin for hide scrollbar

npm install tailwind-scrollbar-hide

utils/cn.ts:

import clsx, { ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export const cn = (...classes: ClassValue[]) => twMerge(clsx(...classes));

Shadcn UI

Beautifully designed components that you can copy and paste into your apps. Accessible.

npx shadcn-ui@latest init

Add icon libraries

npm install lucide-react @radix-ui/react-icons

Dynamically load the lucide icon component.

module.exports = {
  transpilePackages: ['lucide-react'],
}

Adding dark mode

npm install next-themes

Use the add command to add components and dependencies to your project.

npx shadcn-ui@latest add
npx shadcn-ui@latest add [component]

The configuration for Shadcn UI is components.json.

Internationalization (i18n)

Internationalization for react done right. Using the i18next i18n ecosystem.

npm install react-i18next i18next i18next-http-backend

Useful for translating zod error messages.

npm install zod-i18n-map

Trans component rendering for the client side

import { useTrans } from '@/hooks/use-trans'

const { trans: description } = useTrans('key', { 
  components: {
    i: <i />,
    link1: <Link href="#" />,
  },
  values: {
    what: 'world'
  }
})

// translation.json
// { "key": "hello <i>beautiful</i> <link1>{{what}}</link1>" }

The configuration for i18next is i18next.config.ts.

Schema Validation

React Hooks for form state management and validation (Web + React Native).

npm install react-hook-form 
npm install zod @hookform/resolvers

Redux Toolkit

The official, opinionated, batteries-included toolset for efficient Redux development.

npm install @reduxjs/toolkit react-redux

persist and rehydrate a redux store

npm install redux-persist

Supabase Cloud Functions

Run the SQL code in SQL Editor > New Query.

Supabase Auth

Install Supabase packages

npm install @supabase/supabase-js @supabase/ssr

Set environment variables. Edit .env.local:

NEXT_PUBLIC_SUPABASE_URL=<your_supabase_project_url>
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your_supabase_anon_key>

Firebase Auth

Firebase provides the tools and infrastructure you need to develop, grow, and earn money from your app.

# npm ERR! Could not resolve dependency:
# npm ERR! peer firebase-admin@"^11.0.1" from [email protected]
npm install -g firebase-tools
npm install firebase [email protected]

Prompts:

  • Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default instance No
  • Firestore: Configure security rules and indexes files for Firestore Yes
  • Functions: Configure a Cloud Functions directory and its files No
  • Hosting: Configure files for Firebase Hosting and (optionally) Set up GitHub Action deploys No
  • Hosting: Set up GitHub Action deploys No
  • Storage: Configure a security rules file for Cloud Storage Yes
  • Emulators: Set up local emulators for Firebase products Yes
  • Remote Config: Configure a template file for Remote Config No
  • Extensions: Set up an empty Extensions manifest No
  • Frameworks: Get started with Frameworks projects. No
firebase init

Create a new project alias.

firebase list
firebase use --add

Initialize the Firebase emulator.

# hosting: Port 5000 is not open on localhost (127.0.0.1,::1), could not start Hosting Emulator
# Port 5000 and 7000 are taken by airplay on MacOS Monterey.
firebase init emulators

For Mac/Linux, use the Terminal/Shell to find the Process ID (PID), then kill the process.

# Error: Could not start Hosting Emulator, port taken.
lsof -ti tcp:5000 | xargs kill -9 && firebase emulators:start

Start the firebase emulator.

firebase emulators:start

Set the expiration of a preview channel.

firebase init hosting
firebase hosting:channel:deploy preview --expires 1h

Start firebase deployment.

firebase deploy

Text Editor

Powerful rich text editor framework with a modular architecture, modern integrations, and features like collaborative editing.

Download the files from Online Builder and unzip them into the ckeditor5 folder. However, exclude the Watchdog feature.

And run the script below:

npm install file:./ckeditor5
npm install @ckeditor/ckeditor5-react

Utils

Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-preset-env

npm install browserslist

A collection of essential TypeScript types

npm install type-fest

Svg react icons of popular icon packs

npm install react-icons

A modern JavaScript utility library delivering modularity, performance, & extras.

npm install lodash @types/lodash

Generate RFC-compliant UUIDs in JavaScript

npm install uuid @types/uuid

Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API

npm install dayjs

Send e-mails with Node.JS

npm install nodemailer
npm install --save-dev @types/nodemailer

JsonWebToken implementation for node.js

npm install jsonwebtoken @types/jsonwebtoken

ESLint

ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code.

npm install --save-dev eslint eslint-plugin-react eslint-plugin-react-hooks
npm install --save-dev @next/eslint-plugin-next
npm install --save-dev eslint-plugin-import eslint-import-resolver-typescript
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin 
npm install --save-dev prettier eslint-plugin-prettier eslint-config-prettier
npm install --save-dev eslint-plugin-tailwindcss prettier-plugin-tailwindcss

Edit next.config.js:

module.exports = {
  eslint: {
    // Warning: This allows production builds to successfully complete even if
    // your project has ESLint errors.
    ignoreDuringBuilds: true,
  },
}

Find and fix problems in your JavaScript code.

npx eslint ./app
npx eslint --fix ./{app,components,context,hooks,lib,types,utils}

To format a file in-place

npx prettier --check "./app/**/*.{ts,tsx}"
npx prettier --write "./{app,components,context,hooks,lib,types,utils}/**/*.{ts,tsx}"

Configuration

Generating Database Types

Api Docs > Introduction > Generating Types

Edit next.config.js:

module.exports = {
  reactStrictMode: true,
  swcMinify: true,
}

Edit packages.json:

{
    "scripts": {
        "clean:dir": "rm -rf node_modules",
        "clean:cache": "npm cache clean --force",
        "clean": "npm run clean:dir && npm run clean:cache",
        "reinstall": "npm run clean && npm install"
    },
}

To enable Turbopack. Edit packages.json:

{
    "scripts": {
        "dev": "next dev --turbo"
    }
}

After cleaning the directories and cache, install the dependency packages.

npm run --force reinstall

Usage

Register your provider in context/app-provider.tsx.

import { Provider } from '@/context/provider'

const providers = [Provider]

Register your redux store in store/root-reducer.ts.

import reducer from './features/slice'

const rootReducer = combineReducers({
  name: reducer,
})

Data Fetching With JSON

Client side

import { fetcher } from '@/lib/utils'

const onSubmit = async (formValues: FormValues) => {
  const { data, error } = await fetcher<FetchData>('https://...', {
    method: 'POST',
    body: JSON.stringify(formValues),
  })
}

Server side: route.ts

import { NextResponse, type NextRequest } from 'next/server'

export async function POST(request: NextRequest) {
  const body = await request.json()
  return NextResponse.json({ body })
}

Data Fetching With FormData

Client side

import { fetcher } from '@/lib/utils'

const onSubmit = async (formValues: FormValues) => {
  const formData = new FormData()
  formData.append('email', formValues?.email)
  const { data, error } = await fetcher<FetchData>('https://...', {
    method: 'POST',
    body: formData,
  })
}

Server side: route.ts

import { NextResponse, type NextRequest } from 'next/server'

export async function POST(request: NextRequest) {
  const formData = await request.formData()
  const email = formData.get('email') as string
  return NextResponse.json({ email })
}

Error Handling

import { Button } from '@/components/ui/button'

export function Component() {
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false)
  
  const onSubmit = async (formValues: FormValues) => {
    setIsSubmitting(true)
    try {
      const { data, error } = await fetch('https://...').then((res) => res.json())
      if (error) throw new Error(error?.message)
      // ...
    } catch (e: unknown) {
      console.error((e as Error)?.message)
    } finally {
      setIsSubmitting(false)
    }
  }
  
  return <Button disabled={isSubmitting}>Submit</Button>
}

Deploying

Deploy app to Vercel

vercel deploy

Deploying Static Exports next.config.js:

module.exports = {
  output: 'export',
  exportTrailingSlash: true,
  assetPrefix: '/out',
}

Dependency packages in production for deployment on Vercel hosting.

npm install @vercel/analytics

(Optional) Vercel Speed Insights package

npm install @vercel/speed-insights

(Optional) Image Optimization

Usage image component

import Image from 'next/image'

export default function Page() {
  return <Image />
}

Set image element rules in .eslintrc.js:

module.exports = {
  rules: {
    '@next/next/no-img-element': 'warn',
  }
}

Troubleshooting

...

Reference

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.