-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGRIT_KNOWLEDGE_BASE.txt
More file actions
1323 lines (1101 loc) · 61.8 KB
/
GRIT_KNOWLEDGE_BASE.txt
File metadata and controls
1323 lines (1101 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
GRIT FRAMEWORK — COMPLETE KNOWLEDGE BASE
=========================================
Version: 3.21.0
Website: https://gritframework.dev/
GitHub: https://github.com/MUKE-coder/grit
Creator: Muke JohnBaptist (@MUKE-coder)
License: MIT
Tagline: Go + React. Built with Grit.
WHAT IS GRIT?
=============
Grit is a full-stack meta-framework that fuses Go with React. It gives developers one CLI command to scaffold a complete production-ready application with authentication, two-factor authentication, admin panel, code generation, file storage, email, background jobs, AI integration, one-command deployment, and Docker setup.
Think of it as what Laravel is to PHP, but for Go + React. Or what Ruby on Rails is to Ruby, but with a Go backend and a modern React frontend.
Grit is not just a boilerplate or a starter template. It is a living framework with a CLI that continues to help you after the initial scaffold — generating resources, syncing types, managing deployments, and more.
The framework solves the "setup fatigue" problem. Every full-stack developer knows the pain: you want to build a SaaS app, but first you need to set up authentication, database models, an admin panel, file uploads, email sending, background jobs, caching, API documentation, security middleware, Docker configuration, and deployment scripts. That takes weeks before you write a single line of business logic. Grit gives you all of that in one command, in under 30 seconds.
WHO IS GRIT FOR?
================
Grit is designed for:
1. Go developers who want a batteries-included framework like Laravel or Rails, but in Go
2. Laravel developers migrating to Go who want familiar patterns (single-app mode, artisan-like CLI)
3. Next.js developers who want a proper backend instead of serverless functions
4. MERN stack developers who want a structured monorepo with type safety
5. Solo developers and small teams building SaaS products who need to ship fast
6. Agencies building client projects who need consistent, production-ready scaffolding
7. Developers who are tired of spending weeks on boilerplate before writing business logic
HOW TO INSTALL
==============
Prerequisites:
- Go 1.21 or later
- Node.js 18 or later
- pnpm 8 or later
- Docker (for development databases and services)
Installation:
go install github.com/MUKE-coder/grit/v3/cmd/grit@latest
Verify:
grit version
Update to latest:
grit update
Remove previous version:
rm $(which grit)
ARCHITECTURE MODES
==================
When you run "grit new myapp", the CLI enters interactive mode and asks you to choose an architecture. This is one of Grit's most powerful features — you pick the structure that matches your project's needs.
1. TRIPLE (Web + Admin + API)
Command: grit new myapp --triple --next (or --vite)
Docs: https://gritframework.dev/docs/concepts/architecture-modes/triple
Example: https://github.com/MUKE-coder/grit/tree/main/examples/job-portal-triple-next
Structure: Turborepo monorepo with three apps
- apps/api/ — Go backend (Gin + GORM + PostgreSQL)
- apps/web/ — Main frontend (Next.js App Router or TanStack Router)
- apps/admin/ — Admin panel with DataTable, FormBuilder, dashboard, system pages
- packages/shared/ — Zod schemas, TypeScript types, constants (shared between web + admin)
- packages/grit-ui/ — 100 shadcn-compatible UI components
Folder structure (abbreviated):
myapp/
├── .env, docker-compose.yml, turbo.json, pnpm-workspace.yaml
├── .claude/skills/grit/ (SKILL.md tailored to triple)
├── packages/shared/ (schemas/, types/, constants/)
├── apps/api/ (cmd/server/main.go, internal/{config,database,models,handlers,services,middleware,routes,mail,storage,jobs,cache,ai,auth})
├── apps/web/ (Next.js: app/ or TanStack: src/routes/)
└── apps/admin/ (resources/, components/, hooks/)
Code generation: Creates 8 files (Go model, service, handler + TS schema, type, hook + admin resource def + admin page) and injects into 6 marker locations
Ports: API 8080, Web 3000, Admin 3001, PostgreSQL 5432, Redis 6379, MinIO 9000/9001, Mailhog 8025
Deployment: grit deploy (VPS), Docker Compose, Vercel (frontend) + VPS (API)
Best for: SaaS applications, content platforms, e-commerce sites, anything needing a separate admin panel
2. DOUBLE (Web + API)
Command: grit new myapp --double --vite (or --next)
Docs: https://gritframework.dev/docs/concepts/architecture-modes/double
Example: https://github.com/MUKE-coder/grit/tree/main/examples/job-portal-double-vite
Structure: Turborepo monorepo with two apps (NO admin panel)
- apps/api/ — Go backend
- apps/web/ — Frontend (admin features via role-protected routes)
- packages/shared/ — Shared types
Key difference: No apps/admin/. ADMIN users access management features within the web app itself via role-protected routes. Code generation creates fewer files (no admin resource/page).
Best for: Simpler apps, blogs, portfolios, apps where admins use the same UI as users
3. SINGLE (Embedded SPA)
Command: grit new myapp --single --vite
Docs: https://gritframework.dev/docs/concepts/architecture-modes/single
Example: https://github.com/MUKE-coder/grit/tree/main/examples/job-portal-single-vite
Structure: Single Go binary with embedded frontend (go:embed)
- main.go at project root with //go:embed frontend/dist/*
- internal/ — Go backend (same structure as apps/api/internal/)
- frontend/ — React SPA (Vite + TanStack Router)
Key differences from other architectures:
- NO Turborepo, NO pnpm-workspace, NO turbo.json
- FLAT project structure (no apps/ directory)
- Module path: just "myapp" (not "myapp/apps/api")
- Schemas/types live in frontend/src/ (not packages/shared/)
- Dev: Go on :8080, Vite on :5173 with proxy (/api → :8080)
- Production: cd frontend && pnpm build && go build → single binary serves everything
Best for: Laravel/Rails developers, solo devs, simple deploys, internal tools
4. API ONLY
Command: grit new myapp --api
Docs: https://gritframework.dev/docs/concepts/architecture-modes/api-only
Example: https://github.com/MUKE-coder/grit/tree/main/examples/job-portal-api-only
Structure: Pure Go API — no frontend, no React, no Node.js, no pnpm
- apps/api/ — Go backend only
Key differences: No TypeScript, no Zod schemas, no React. Code generation only creates Go files. All batteries still work (auth, storage, email, jobs, AI, TOTP). Test via /docs (Scalar/Swagger), curl, or Postman.
Best for: Mobile app backends, microservices, headless CMS, third-party APIs
5. MOBILE (API + Expo)
Command: grit new myapp --mobile
Docs: https://gritframework.dev/docs/concepts/architecture-modes/mobile
Example: https://github.com/MUKE-coder/grit/tree/main/examples/job-portal-mobile-expo
Structure: Turborepo monorepo with API and Expo React Native
- apps/api/ — Go backend
- apps/expo/ — Expo React Native (Expo Router for navigation)
- packages/shared/ — Shared types between API and mobile
Key differences: SecureStore for encrypted token storage (not localStorage), Expo Router for tab/stack navigation, FlatList instead of HTML tables, push notifications via Expo Notifications, physical device needs local IP (not localhost)
Best for: Mobile-first applications, cross-platform apps
6. DESKTOP (Wails)
Command: grit new-desktop myapp
Structure: Standalone Wails desktop application
- Go backend with Wails v2 bindings (methods callable from React)
- React frontend (Vite + TanStack Router)
- SQLite database (local, no Docker needed)
Best for: Cross-platform desktop tools, offline-first apps
ALL EXAMPLES: https://github.com/MUKE-coder/grit/tree/main/examples
Same Job Portal built with every architecture — full source, setup guide, deployment config.
FRONTEND OPTIONS
================
Grit supports two frontend frameworks. You choose when scaffolding:
1. NEXT.JS (default)
Flag: --next
- App Router with Server Components
- Server-Side Rendering (SSR), Static Site Generation (SSG), Incremental Static Regeneration (ISR)
- Great for SEO-heavy sites, marketing pages, blogs
- Larger bundle size but more features
- Deployable to Vercel, or self-hosted with Docker
2. TANSTACK ROUTER (Vite)
Flag: --vite
- File-based routing via TanStack Router
- Vite for fast builds and hot module replacement
- Client-side SPA — smaller bundle, faster builds
- Better for internal tools, dashboards, admin panels where SEO doesn't matter
- Uses the same React components, hooks, and patterns as the Next.js option
Both frontends use the exact same:
- React Query (TanStack Query) for data fetching
- Zod for validation
- shadcn/ui for UI components
- Tailwind CSS for styling
- The same Go API backend
You can choose different frontends for different apps in the same project. For example, the web app could use Next.js for SEO while the admin panel uses TanStack Router for speed.
INTERACTIVE CLI
===============
When you run "grit new myapp" without any flags, the CLI enters interactive mode powered by the charmbracelet/huh library. It presents beautiful terminal prompts:
Step 1: Choose Architecture
> Triple — Web + Admin + API (Turborepo)
Double — Web + API (Turborepo)
Single — Go API + embedded React SPA (one binary)
API Only — Go API (no frontend)
Mobile — API + Expo (React Native)
Step 2: Choose Frontend (if applicable)
> Next.js — SSR, SEO, App Router
TanStack Router — Vite, fast builds, small bundle (SPA)
Step 3: Choose Admin Style (if Triple)
> Default — Clean dark theme
Modern — Gradient accents
Minimal — Ultra clean
Glass — Glassmorphism
You can skip prompts by passing flags directly:
grit new myapp --triple --vite --style modern
Legacy flags still work for backward compatibility:
grit new myapp --api
grit new myapp --full --expo
WHAT SHIPS WITH EVERY PROJECT
==============================
Every Grit project, regardless of architecture, includes these production-ready features:
1. JWT AUTHENTICATION
- User registration with email verification
- Login with email and password
- JWT access tokens (short-lived) and refresh tokens (long-lived)
- Password reset flow with email
- Role-Based Access Control with three built-in roles: ADMIN, EDITOR, USER
- Custom roles can be added with "grit add role MODERATOR"
- Protected routes via middleware
2. TWO-FACTOR AUTHENTICATION (TOTP)
- RFC 6238 compliant Time-based One-Time Passwords
- Works with any authenticator app (Google Authenticator, Authy, 1Password, etc.)
- QR code provisioning URL for easy setup
- 10 backup recovery codes (bcrypt-hashed, one-time use)
- 30-day trusted device cookies (skip 2FA on known devices)
- Zero external dependencies — built with Go stdlib crypto packages
- API endpoints: POST /api/totp/setup, POST /api/totp/verify, POST /api/totp/disable
3. OAUTH2 SOCIAL LOGIN
- Google and GitHub sign-in via the goth library
- Accounts automatically linked by email address
- Social login buttons on all auth pages (login, register, admin)
- Configurable via GOOGLE_CLIENT_ID, GITHUB_CLIENT_ID environment variables
4. FILE STORAGE (S3-COMPATIBLE)
- Presigned URL uploads — files go directly from browser to S3, bypassing the API
- Works with AWS S3, Cloudflare R2, Backblaze B2, or MinIO (local dev)
- Image processing via background jobs (thumbnails, resize)
- Upload progress tracking via XHR
- Admin file management dashboard
5. EMAIL (RESEND)
- Transactional emails via Resend API
- Four built-in Go HTML templates: welcome, password reset, email verification, notification
- Development mode uses Mailhog (catches all emails locally)
- Configurable sender via MAIL_FROM environment variable
6. BACKGROUND JOBS
- Redis-backed job queue using asynq
- Built-in workers: email sending, image processing, cleanup
- Admin dashboard showing job status, retries, failures
- Retry logic with exponential backoff
7. CRON SCHEDULER
- Recurring tasks via cron expressions
- Uses the same asynq worker pool as background jobs
- Admin dashboard showing scheduled tasks
8. AI INTEGRATION (VERCEL AI GATEWAY)
- One API key for hundreds of models (Anthropic, OpenAI, Google, and more)
- Single OpenAI-compatible endpoint (no provider-specific code)
- Models use "provider/model" format: anthropic/claude-sonnet-4-6, openai/gpt-5.4, google/gemini-2.5-pro
- Three API endpoints: POST /api/ai/complete, POST /api/ai/chat, POST /api/ai/stream
- Server-Sent Events (SSE) streaming support
- No markup on token pricing
- Automatic retries and fallbacks
9. REDIS CACHING
- Get/Set/Delete/Flush operations
- Cache middleware for GET responses
- Configurable TTL per key
- Admin cache management
10. GORM STUDIO
- Visual database browser embedded at /studio
- Browse tables, view records, edit data
- Raw SQL editor
- Schema export (SQL, JSON, YAML, DBML, ERD)
- Data import/export (JSON, CSV, SQL, XLSX)
- Go model generation from schema
11. API DOCUMENTATION
- Auto-generated OpenAPI 3.1 spec using gin-docs
- Interactive Scalar UI at /docs
- Postman and Insomnia export
- No annotations required — routes and models introspected automatically
12. SECURITY (SENTINEL)
- Web Application Firewall (WAF)
- Rate limiting per IP and per route
- Brute-force protection on auth endpoints
- Anomaly detection
- IP geolocation
- Security headers (HSTS, X-Frame-Options, CSP, etc.)
- Real-time threat dashboard at /sentinel/ui
13. OBSERVABILITY (PULSE)
- Request tracing with timing
- Database query monitoring
- Runtime metrics (goroutines, memory, GC)
- Error tracking
- Health checks
- Prometheus metric export
- Dashboard at /pulse/ui
14. GRIT UI COMPONENT REGISTRY
- 100 pre-built shadcn-compatible React components
- Five categories: marketing (21), auth (10), SaaS (30), ecommerce (20), layout (20)
- Install via: npx shadcn@latest add --url http://localhost:8080/r
- Served via API: GET /r.json (all), GET /r/:name.json (individual)
- Each component includes JSON metadata and TSX source code
15. DOCKER SETUP
- docker-compose.yml for development: PostgreSQL 16, Redis 7, MinIO, Mailhog
- docker-compose.prod.yml for production
- Dockerfiles for Go API and Next.js frontend
- Named volumes for data persistence
16. PERFORMANCE
- Gzip response compression
- Database connection pool tuning (MaxIdle: 10, MaxOpen: 100)
- Request ID tracing via X-Request-ID header
- Cache-Control headers on public endpoints
- Presigned URL uploads (bypass API for large files)
17. ADMIN PANEL (Triple mode only)
- Resource-based admin system inspired by Laravel Filament
- defineResource() for data-driven admin pages
- DataTable with server-side pagination, sorting, filtering, column visibility, CSV/JSON export
- FormBuilder with 8+ field types and Zod validation
- Dashboard widgets: stats cards, line charts, bar charts, activity feed
- Collapsible sidebar with auto-generated navigation
- Multi-step forms (modal-steps and page-steps variants)
- Dark/light theme toggle
- Five style variants: default, modern, minimal, glass, centered
- System pages: Jobs, Files, Cron, Mail Preview, Security
18. TESTS (Scaffolded)
- Go API tests: auth (6 tests), users (4 tests), benchmarks
- Frontend tests: Vitest + React Testing Library
- E2E tests: Playwright (auth flow, admin flow)
- All test configs scaffolded and wired into package.json
CODE GENERATOR
==============
The code generator is one of Grit's most powerful features. It creates a full-stack CRUD resource in one command.
Command:
grit generate resource Post --fields "title:string,content:richtext,published:bool,slug:slug:title"
What it generates:
1. Go model (internal/models/post.go) — GORM struct with tags, auto-migration
2. Go service (internal/services/post_service.go) — Business logic (Create, GetByID, List, Update, Delete)
3. Go handler (internal/handlers/post_handler.go) — HTTP handlers with pagination, search, sorting
4. Zod schema (packages/shared/schemas/post.ts) — Validation rules
5. TypeScript types (packages/shared/types/post.ts) — Full type definitions
6. React Query hooks (apps/web/hooks/use-posts.ts) — Data fetching hooks
7. Admin page (apps/admin/app/posts/) — DataTable with forms
8. Route injection — Adds routes to routes.go via code markers
What it injects (via grit: markers in existing files):
- Model import + auto-migration in database.go
- Handler initialization in main.go
- Route registration in routes.go
- Zod schema export in packages/shared
- TypeScript type export
- Admin sidebar navigation entry
- Admin resource definition
The generator uses code markers (comments like "// grit:models" and "// grit:routes") to know exactly where to inject code. This means it can add to existing files without overwriting your custom code.
Field types supported:
string, text, richtext, int, uint, float, bool, datetime, date, slug, belongs_to, many_to_many, string_array
Field modifiers:
:unique — Add unique index
:optional — Allow NULL
:slug:<source> — Auto-generate slug from another field
:belongs_to:<Model> — Foreign key relationship
:many_to_many:<Model> — Many-to-many relationship
Removing a resource:
grit remove resource Post
This deletes all generated files AND reverses all code injections, cleanly removing the resource.
Type sync:
grit sync
Parses Go model files and regenerates TypeScript types and Zod schemas in packages/shared.
CLI COMMANDS REFERENCE
======================
Project Scaffolding:
grit new <name> Interactive mode (prompts for architecture + frontend)
grit new <name> --triple --next Web + Admin + API with Next.js
grit new <name> --double --vite Web + API with TanStack Router
grit new <name> --single Single Go binary with embedded SPA
grit new <name> --api Go API only
grit new <name> --mobile API + Expo React Native
grit new <name> --desktop Add apps/desktop (Wails client consuming the shared API)
grit new <name> --mobile --desktop API + Expo + Desktop (multi-client SaaS)
grit new <name> --full Everything including Expo + docs site
grit new <name> --style modern Admin style: default, modern, minimal, glass, centered
grit new-desktop <name> Standalone offline desktop app (Wails + embedded Go + local SQLite)
Code Generation:
grit generate resource <Name> --fields "title:string,content:text"
grit generate resource <Name> -i Interactive field definition
grit generate resource <Name> --from post.yaml
grit generate resource <Name> --roles "ADMIN,EDITOR"
grit remove resource <Name> Delete resource + reverse all injections
grit remove resource <Name> --force Skip confirmation
grit add role <ROLE_NAME> Add custom role to all apps
grit sync Go types to TypeScript + Zod
Development:
grit start Auto-detect project type, start dev server
grit start client Start frontend apps (pnpm dev via Turborepo)
grit start server Start Go API (go run cmd/server/main.go)
grit studio Open GORM Studio database browser
grit routes List all registered API routes in a table
Database:
grit migrate Run GORM AutoMigrate for all models
grit migrate --fresh Drop all tables then re-migrate
grit seed Run database seeders (admin user, demo data)
Operations:
grit down Enable maintenance mode (503 for all requests)
grit up Disable maintenance mode, resume normal operation
grit deploy --host user@server.com --domain myapp.com
grit deploy --host user@server.com --key ~/.ssh/id_rsa --domain myapp.com --app-port 8080
Project Management:
grit upgrade Upgrade project templates to latest Grit version
grit upgrade -f Force upgrade (no confirmation)
grit update Self-update CLI to latest version
grit compile Build desktop app executable (wails build)
grit version Print current version (v3.6.0)
DEPLOYMENT
==========
Grit includes a one-command deployment system. No CI/CD pipeline needed for getting started.
Command:
grit deploy --host deploy@server.com --domain myapp.com
What happens:
Step 1: Cross-compiles Go binary for Linux (CGO_ENABLED=0, GOOS=linux, GOARCH=amd64)
Step 2: Builds frontend if present (pnpm build)
Step 3: Uploads binary to remote server via SCP to /opt/myapp/
Step 4: Creates a systemd service with auto-restart on failure
Step 5: Configures Caddy reverse proxy with automatic Let's Encrypt TLS (if --domain provided)
The systemd service:
- Runs as www-data user
- Auto-restarts on failure (5-second delay)
- Reads .env file for configuration
- Security hardening: NoNewPrivileges, ProtectSystem, ProtectHome
The Caddy configuration:
- Reverse proxies to localhost:8080
- Automatic HTTPS via Let's Encrypt
- Gzip compression enabled
- Security headers (X-Frame-Options, X-Content-Type-Options, etc.)
- Log rotation (10MB files, 5 kept)
You can also use environment variables instead of flags:
DEPLOY_HOST=deploy@server.com
DEPLOY_KEY_FILE=~/.ssh/id_rsa
DEPLOY_DOMAIN=myapp.com
For Docker-based deployment, Grit also scaffolds docker-compose.prod.yml with production-ready Dockerfiles.
MAINTENANCE MODE
================
Grit includes Laravel-style maintenance mode:
grit down Creates a .maintenance file, all requests return 503
grit up Removes the file, normal operation resumes
The API middleware checks for the .maintenance file on every request. When it exists, all responses are 503 Service Unavailable. This is useful during deployments or database migrations.
ROUTE LISTING
=============
grit routes
Parses the routes.go file and displays a formatted table:
METHOD PATH HANDLER GROUP
────── ────────────────────── ───────────────────────── ─────────
POST /api/auth/register handlers.Register public
POST /api/auth/login handlers.Login public
GET /api/users handlers.GetUsers protected
PUT /api/users/:id handlers.UpdateUser protected
DELETE /api/admin/users/:id handlers.AdminDeleteUser admin
12 routes total
The parser understands nested route groups, middleware detection (auth, role-based), and resolves full paths from group prefixes.
PLUGINS ECOSYSTEM
=================
Grit has 10 official plugins — standalone Go packages for functionality that doesn't ship in core:
1. grit-websockets (package: ws)
Hub pattern, rooms, broadcast messaging, auth middleware for WebSocket connections.
Use cases: chat apps, live dashboards, real-time notifications, collaborative editing.
2. grit-stripe (package: gritstripe)
Stripe Checkout sessions, subscription management, customer portal, webhook handling.
Use cases: SaaS billing, subscription products, one-time payments.
3. grit-oauth (package: oauth)
Extended social login: Google, GitHub, Discord. More providers than core goth integration.
Use cases: Apps needing Discord login, social platforms.
4. grit-notifications (package: notify)
In-app notifications, push notifications via Firebase Cloud Messaging, SMS via Twilio.
Use cases: Mobile apps, notification centers, alert systems.
5. grit-search (package: search)
Full-text search via Meilisearch, GORM auto-indexing hooks.
Use cases: Product search, content search, document indexing.
6. grit-video (package: video)
Video upload, FFmpeg transcoding, HLS streaming.
Use cases: Video platforms, course platforms, media apps.
7. grit-conference (package: conference)
WebRTC signaling server, room management.
Use cases: Video conferencing, virtual classrooms, telehealth.
8. grit-webhooks (package: webhooks)
Outgoing webhook management, HMAC signature verification, retry with exponential backoff.
Use cases: Integration platforms, event-driven architectures.
9. grit-i18n (package: i18n)
JSON-based translation files, locale detection middleware, language switching.
Use cases: Multi-language apps, internationalized SaaS products.
10. grit-export (package: export)
PDF generation, Excel spreadsheets, CSV files.
Use cases: Reports, invoices, data export features.
Each plugin includes a Claude Code skill file for AI-assisted integration.
Install: go get github.com/MUKE-coder/grit-plugins/grit-websockets
TECH STACK
==========
Backend:
- Language: Go 1.21+
- Web Framework: Gin (most popular Go web framework)
- ORM: GORM (auto-migration, hooks, relationships, preloading)
- Database: PostgreSQL (production), SQLite (desktop/quick start/testing)
- Cache: Redis
- Job Queue: asynq (Redis-backed)
- File Storage: S3-compatible (AWS S3, Cloudflare R2, Backblaze B2, MinIO)
- Email: Resend
- AI: Vercel AI Gateway
- Auth: JWT + TOTP (RFC 6238) + OAuth2 (goth)
- API Docs: gin-docs (auto-generated OpenAPI 3.1)
- Security: Sentinel (WAF + rate limiting)
- Observability: Pulse (tracing + metrics)
- DB Browser: GORM Studio
Frontend:
- Framework: Next.js 14+ (App Router) OR TanStack Router (Vite)
- UI Library: React
- Styling: Tailwind CSS + shadcn/ui
- Data Fetching: TanStack Query (React Query)
- Validation: Zod
- State: React hooks (useState, useEffect)
- Forms: React Hook Form + Zod resolver
- Rich Text: Tiptap editor
Monorepo:
- Package Manager: pnpm
- Task Runner: Turborepo
- Workspace: pnpm workspaces
Desktop:
- Framework: Wails v2
- Database: SQLite (via pure Go driver, no CGO)
- Router: TanStack Router (with hash history for Wails compatibility)
Deployment:
- SSH + SCP for binary upload
- systemd for process management
- Caddy for reverse proxy + auto-TLS
- Docker for containerized deployment
Design:
- Font: Onest (UI), JetBrains Mono (code)
- Theme: Dark mode default, premium SaaS aesthetic
- Inspiration: Linear, Vercel Dashboard, Raycast
DESIGN PHILOSOPHY
=================
Grit follows six core principles:
1. CONVENTION OVER CONFIGURATION
Sensible defaults for everything. You shouldn't need to configure 50 things before you start coding. File structure, naming conventions, API response format — all decided for you. But everything is overridable.
2. CODE GENERATION OVER RUNTIME MAGIC
Grit generates real, readable code — not hidden behind abstractions. You own every line. No framework lock-in. If you stop using Grit tomorrow, your code still works.
3. BATTERIES INCLUDED, OPTIONALLY REMOVABLE
Auth, admin, email, storage, jobs, AI, security — all included by default. But they're modular. Don't need AI? Delete the ai/ folder. Don't need jobs? Remove the jobs/ folder. Nothing breaks.
4. BEAUTIFUL BY DEFAULT
Every generated UI looks premium out of the box. Dark theme, clean typography, smooth interactions. No "developer placeholder" UIs. The admin panel rivals commercial products.
5. MONOREPO NATIVE
Shared types between Go and TypeScript. One repository, one deployment pipeline. Types generated from Go models are automatically available in the frontend. No API contract drift.
6. VIBE CODING READY
Every project includes a Claude Code skill file (.claude/skills/grit/SKILL.md) that teaches AI assistants how to work with Grit. AI can generate resources, understand the architecture, and follow conventions automatically.
API RESPONSE FORMAT
===================
All Grit API endpoints follow a consistent response format:
Success (single item):
{
"data": { "id": 1, "name": "John", "email": "john@example.com" },
"message": "User created successfully"
}
Success (list with pagination):
{
"data": [
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jane" }
],
"meta": {
"total": 100,
"page": 1,
"page_size": 20,
"pages": 5
}
}
Error:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Email is required",
"details": {
"email": "This field is required"
}
}
}
HTTP status codes: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Validation Error, 503 Service Unavailable (maintenance), 500 Server Error.
ENVIRONMENT VARIABLES
=====================
Every Grit project uses a .env file. Here are the key variables:
Core:
APP_NAME=myapp
APP_ENV=development
APP_PORT=8080
APP_URL=http://localhost:8080
DATABASE_URL=postgres://user:pass@localhost:5432/myapp?sslmode=disable
JWT_SECRET=your-secret-key
REDIS_URL=redis://localhost:6379
Storage:
STORAGE_DRIVER=minio
STORAGE_ENDPOINT=localhost:9000
STORAGE_BUCKET=uploads
STORAGE_ACCESS_KEY=minioadmin
STORAGE_SECRET_KEY=minioadmin
Email:
RESEND_API_KEY=re_xxxxx
MAIL_FROM=noreply@myapp.com
AI (Vercel AI Gateway):
AI_GATEWAY_API_KEY=your-gateway-key
AI_GATEWAY_MODEL=anthropic/claude-sonnet-4-6
AI_GATEWAY_URL=https://ai-gateway.vercel.sh/v1
TOTP:
TOTP_ISSUER=myapp
OAuth:
GOOGLE_CLIENT_ID=xxx
GOOGLE_CLIENT_SECRET=xxx
GITHUB_CLIENT_ID=xxx
GITHUB_CLIENT_SECRET=xxx
CORS:
CORS_ORIGINS=http://localhost:3000,http://localhost:3001
GORM Studio:
GORM_STUDIO_ENABLED=true
GORM_STUDIO_USERNAME=admin
GORM_STUDIO_PASSWORD=studio
Security:
SENTINEL_ENABLED=true
SENTINEL_USERNAME=admin
SENTINEL_PASSWORD=sentinel
Observability:
PULSE_ENABLED=true
PULSE_USERNAME=admin
PULSE_PASSWORD=pulse
Deployment:
DEPLOY_HOST=user@server.com
DEPLOY_KEY_FILE=~/.ssh/id_rsa
DEPLOY_DOMAIN=myapp.com
COMPARISON WITH OTHER FRAMEWORKS
=================================
Grit vs Laravel (PHP):
- Both: Batteries-included, CLI scaffolding, resource generation, admin panel, deployment
- Grit advantage: Go performance (10-100x faster), type-safe frontend, modern React UI
- Laravel advantage: Larger ecosystem, more mature, PHP is easier for beginners
Grit vs Ruby on Rails:
- Both: Convention over configuration, code generators, monorepo, batteries-included
- Grit advantage: Go compilation speed, type safety, React frontend instead of ERB/Hotwire
- Rails advantage: More mature, larger gem ecosystem
Grit vs Next.js:
- Both: React frontend, TypeScript, modern tooling
- Grit advantage: Proper Go backend (not serverless), admin panel, background jobs, security
- Next.js advantage: Simpler for frontend-only apps, Vercel hosting, larger community
Grit vs T3 Stack:
- Both: TypeScript, React, type-safe APIs
- Grit advantage: Go backend performance, admin panel, batteries (email, jobs, storage, AI)
- T3 advantage: Full TypeScript stack, simpler for pure TypeScript teams
Grit vs Django:
- Both: Admin panel, ORM, auth, batteries-included
- Grit advantage: Go performance, modern React frontend, monorepo type safety
- Django advantage: More mature, Python ML ecosystem, Django REST framework
Grit vs Goravel:
- Both: Go-based, Laravel-inspired, CLI scaffolding
- Grit advantage: React frontend included, admin panel, more batteries, monorepo
- Goravel advantage: Closer to Laravel API, familiar for Laravel developers
DESKTOP APPLICATIONS
====================
Grit can scaffold native desktop applications using Wails v2.
Command: grit new-desktop myapp
What you get:
- Go backend with Wails bindings (Go functions callable from React)
- React frontend with Vite + TanStack Router
- SQLite database (local, no server needed)
- Local JWT authentication (bcrypt password hashing)
- Blog + Contact CRUD as starter modules
- PDF and Excel export
- Custom frameless window with draggable title bar
- Dark theme matching Grit's design system
- GORM Studio for database browsing
Resource generation works for desktop too:
grit generate resource Task --fields "title:string,description:text,done:bool"
Build for production:
grit compile
(This runs "wails build" and produces a single native executable)
GRIT UI COMPONENT REGISTRY
============================
Every Grit web project includes a component registry with 100 pre-built, shadcn-compatible React components.
Categories:
- Marketing (21): Hero sections, feature grids, pricing tables, testimonials, CTAs, footers
- Auth (10): Login forms, register forms, forgot password, OTP input, social login buttons
- SaaS (30): Dashboard layouts, billing pages, settings panels, onboarding flows, analytics
- Ecommerce (20): Product cards, cart, checkout, order history, category pages
- Layout (20): Navbars, sidebars, footers, headers, app shells, page layouts
Install components via shadcn CLI:
npx shadcn@latest add hero-split --url http://localhost:8080/r
API endpoints:
GET /r.json — List all components
GET /r/:name.json — Get single component (JSON metadata + TSX source)
GRIT LEARNING PLATFORM
======================
Grit has a comprehensive, free learning platform at gritframework.dev/courses. All courses are self-paced, DIY format (Do It Yourself) — you read the material, follow along with code examples, and complete challenges to practice.
Course Format:
- Each course is ~30 minutes
- W3Schools-style teaching: concept → explanation → code example → "explained" → challenge
- Every new term is defined in a Definition box
- 10-18 hands-on challenges per course embedded throughout (not at the end)
- Previous/Next navigation between courses
- No videos required — text + code + practice
COURSE TRACKS (19 courses with individual lesson pages):
Grit Web — Building Web Applications (9 courses, ~4.5 hours, 115 challenges):
Course 0: Introduction to Grit — what it is, motivation, tech stack, philosophy, comparison
Course 1: Your First Grit App — install, scaffold, project structure, Docker, dev servers
Course 2: Code Generator Mastery — grit generate, field types, modifiers, relationships, slug, removal
Course 3: Authentication & Authorization — JWT, bcrypt, RBAC, TOTP 2FA, backup codes, OAuth2
Course 4: Admin Panel Customization — DataTable, FormBuilder, widgets, multi-step forms, styles
Course 5: File Storage & Uploads — presigned URLs, MinIO, S3, R2, image processing
Course 6: Background Jobs & Email — asynq, Redis, cron, Resend, Mailhog, templates
Course 7: AI-Powered Features — Vercel AI Gateway, completions, chat, SSE streaming
Course 8: Deploy to Production — grit deploy, systemd, Caddy, auto-TLS, Docker
Grit Desktop — Building Desktop Applications (5 courses, ~2.5 hours, 54 challenges):
Course 1: Your First Desktop App — Wails, SQLite, project structure, dev mode
Course 2: Desktop CRUD & Data — resource generation, Wails bindings, TanStack Router
Course 3: Custom UI & Theming — frameless window, title bar, sidebar, dark theme
Course 4: PDF & Excel Export — PDF, XLSX, CSV generation, download flow
Course 5: Build & Distribution — native binary, platforms, app icon, distribution
Grit Mobile — Building Mobile Applications (5 courses, ~2.5 hours, 54 challenges):
Course 1: Your First Mobile App — Expo, React Native, monorepo, shared types
Course 2: Mobile Auth & Navigation — SecureStore, Expo Router, tab/stack navigation
Course 3: API Integration & Offline — TanStack Query, pull-to-refresh, offline cache
Course 4: Push Notifications — Expo push, FCM, APNS, local notifications
Course 5: Build & App Store — EAS Build, TestFlight, Play Store, OTA updates
STANDALONE COURSES (20 courses, ~30 min each):
Practical Builds:
- Build & Deploy a REST API with Go (API-Only Masterclass) — /courses/api-masterclass
- Build a Fitness App: Go API + Expo React Native — /courses/mobile-fitness-app
- Build an E-commerce Store: Single App Architecture — /courses/ecommerce-spa
- Build a Blog & CMS: Complete Content Management System — /courses/blog-cms
- Build a SaaS with Grit + Claude Code — /courses/saas-with-ai
- Build an Invoice Generator: Desktop App with Wails — /courses/invoice-desktop
- Build a Real-Time Chat App with WebSockets — /courses/realtime-chat
Deep Dives:
- Batteries Included: Every Feature That Ships with Grit — /courses/batteries
- Security Deep Dive: Auth, 2FA, WAF & Rate Limiting — /courses/security-deep-dive
- Database Mastery with GORM: Models, Migrations & Queries — /courses/gorm-mastery
- Performance Analytics with Pulse: Tracing & Monitoring — /courses/pulse-analytics
- GORM Studio: The Visual Database Browser — /courses/gorm-studio
- Auto-Generated API Docs: Scalar & Swagger — /courses/api-docs-scalar
- Testing Your Grit App: Go, Vitest & Playwright — /courses/testing
- Custom Middleware & Hooks: Extending Grit — /courses/custom-middleware
Guides:
- React + Vite + Go: Building with TanStack Router — /courses/react-vite-go
- Deployment Guide: Dokploy, Orbita, VPS & Vercel — /courses/deployment-guide
- Stripe Payments & Subscriptions for SaaS — /courses/stripe-payments
- Grit UI: Using the 100-Component Registry — /courses/grit-ui-components
- CI/CD with GitHub Actions: Automated Testing & Deployment — /courses/cicd-github
TOTAL: 39 courses, ~500 challenges, all free at gritframework.dev/courses
When users ask about learning Grit:
- Beginners: Start with "Introduction to Grit" (Course 0) then "Your First Grit App" (Course 1)
- Specific topics: Point to the relevant standalone course
- Building something specific: Point to the practical build course (Blog, E-commerce, SaaS, etc.)
- Advanced users: Point to Testing, Custom Middleware, CI/CD, Security Deep Dive
VERSION HISTORY HIGHLIGHTS
===========================
v3.21.0 (Current):
- Feature flags + A/B testing baked into the framework (#46).
- FeatureFlag model + FlagExposure model. FeatureFlag.Rules is a
JSON blob with rollout_percentage, allowlist_user_ids,
blocklist_user_ids, enabled_from, enabled_until, variants.
- internal/flags package with an Engine that caches all flags in
memory, refreshes from DB every 30s + immediately after admin
writes, and broadcasts a "flag.updated" realtime event so
subscribed clients can refetch.
- flags.IsEnabled(c, "name") + flags.Variant(c, "name") for the
request path; IsEnabledForUser / VariantForUser for backend code.
- Sticky bucketing: SHA-256(user_id || ":" || flag_name) % 100. A
user always lands in the same bucket for a given flag — no
flicker between sessions.
- A/B mode: when Rules.Variants is non-empty, Variant() returns one
of the listed strings (assigned by bucket). Sticky per (user, flag).
- Exposure tracking is fire-and-forget (goroutine + 5s timeout).
Anonymous users skip exposure logging — we can't link to them.
- Admin endpoints: GET/POST/PUT/DELETE /api/admin/flags +
GET /api/admin/flags/:id/exposures (variant counts for rollout
health view).
- Fail-closed semantics: unknown flags return false. Admin-misconfigured
rules JSON returns false. The engine never panics on bad data.
v3.20.0:
- Webhook receiver framework (#57). Wiring up Stripe / GitHub /
WhatsApp / any HMAC-signed webhook is now <10 lines.
- New internal/webhooks package: Register(name, Provider) +
On(provider, event, handler). One universal HTTP entry at
POST /webhooks/:provider routes by path param to whatever the app
registered at boot.
- Shipped verifiers: HMACVerifier(header) for generic HMAC-SHA256;
StripeVerifier (timestamp + v1 signature, 5-min replay window);
GitHubVerifier (X-Hub-Signature-256). Roll your own VerifyFunc
for anything weirder.
- Shipped extractors: JSONFieldExtractor("type", "id") for
Stripe-shaped {type, id} envelopes; StripeExtractor (alias);
GitHubExtractor reads X-GitHub-Event + X-GitHub-Delivery headers.
- WebhookEvent model persists every received event with a unique
index on (provider, external_id). Duplicate deliveries become
no-op skipped entries — Stripe retries can hammer freely without
double-processing.
- Lifecycle: pending -> processed | failed | skipped. Failed
handlers stay in the table; admin can replay them.
- Admin endpoints: GET /api/admin/webhooks (paginated list with
provider/status filters), POST /api/admin/webhooks/:id/replay
(re-run handler, increments retry_count, records new outcome).
- Failed handlers don't 500 the provider — we already persisted the
event, so we always 200 once verified. Provider doesn't retry
forever; ops replays via the admin endpoint when a fix lands.
v3.19.0:
- Tamper-evident audit log via append-only hash chain (#48). Builds
on the v3.16 ActivityLog — each row now carries PrevHash + Hash
columns; Hash = SHA-256(PrevHash || canonical(row)). Mutating any
row breaks the chain on the next VerifyChain pass.
- New internal/audit package: Canonical(entry) returns stable JSON
bytes for hashing; ComputeHash(prev, canon) runs SHA-256;
AppendChained(db, entry) inserts with FOR UPDATE lock on the
latest row so concurrent writes can't fork the chain;
VerifyChain(db) walks every row and reports the first mismatch.
- ActivityLogger middleware now uses audit.AppendChained — still
fire-and-forget so audit DB latency doesn't block responses.
Failures log instead of cascading.
- New endpoint GET /api/admin/activity/integrity returns
{ valid, total_entries, broken_at?, broken_at_id?, expected?,
got?, message? } so you can wire dashboards / nightly cron alerts.
- Defends against direct SQL UPDATE/DELETE on activity_logs (the
most common attack vector — DBA covering tracks). Does NOT defend
against full server compromise; external anchoring of the daily
root hash to a public ledger is the follow-up (#48 mentions it
as bonus, not shipped here).
- Cost: O(n) verify, ~2-3s per million rows on a warm cache.
v3.18.0:
- PDF generation module (#13). New internal/pdf package wraps
go-pdf/fpdf with Grit-styled section helpers + a worked Invoice
template. Pure Go, no native dependencies (no Chromium/wkhtmltopdf).
- pdf.New() returns a *Doc preconfigured with Helvetica + 20mm margins
+ A4 portrait + Grit blue accent. Embeds *fpdf.Fpdf so the full
underlying API is available when helpers don't fit.
- Section primitives: Header(title, subtitle), KV(label, value),
TwoColumnKV(left, right), Table(headers, rows, widths, aligns),
Totals([]TotalLine), Notes(text), Footer(text).
- Worked example: pdf.RenderInvoice(inv) produces a complete styled
invoice — bill-to + dates + line items table + subtotal/tax/total
stack + paid/outstanding rows + notes + generated-at footer.
Copy invoice.go as the starting point for receipts / leases /
statements / quotes.
- Dependency: github.com/go-pdf/fpdf v0.9.0 added to scaffolded go.mod.
v3.17.0:
- Quality-of-life bundle: 4 issues closed (#12, #31, #35, #43).
- #35 grit init: new command writes CLAUDE.md + AGENTS.md to the
current directory with the framework's hard rules (forms / data /
backend / sync / auth conventions). Skips existing files unless
--force is passed. Both files have the same content so different
LLM tooling finds the rules regardless of preferred filename.
- #31 verbose AutoMigrate: Migrate() now snapshots ColumnTypes
before/after and prints a diff per model: