iTranslated by AI
RedwoodJS as a Prototyping Tool
This article introduces RedwoodJS as a tool for creating web application prototypes.
Introduction: Technology Selection in Prototyping
When creating a prototype for a simple web application, what kind of technology stack do you choose?
Even for a prototype, most cases include some level of UI verification, so as the author, I prefer to use React for UI construction[1]. Since template engines significantly reduce development efficiency, full-stack frameworks like Rails or Django cannot be chosen at this point.
However, even if you choose React, most applications require a persistence layer, and there are many pieces of logic you don't want to run on the frontend. When creating the backend separately, you face the issue of how to maintain consistency with the client-side API schema. Ideally, I want typing to work for fetching, so I would use tools like aspida or zodios, but my lazy side keeps wishing for a stack where everything is available from the start.[2]
Many developers have likely faced the dilemma of not wanting to do elaborate configurations for prototyping, yet not being able to sacrifice the development experience for the sake of speed.
Fortunately, in recent years, frameworks that solve these problems have been appearing one after another. Today, I would like to introduce one of them: RedwoodJS.
What is RedwoodJS?
RedwoodJS is a web full-stack framework built with TypeScript / JavaScript.
- React + various useful libraries around React
- GraphQL
- Persistence layer access via Prisma
- Other support provided by Redwood
By combining these, it achieves a very convenient development experience. I won't list them all individually here, but looking at the repository or the documentation will show you just how feature-rich a framework RedwoodJS is.
A Gracious Word from RedwoodJS
Let's look at the words displayed on the top page.
Focus on building your startup, not fighting your framework.
What a reassuring statement.
It sounds like a message directed at me, who was grumbling, "I can't spend time on tedious configurations in a prototyping project, but the development experience..."
Why it's convenient
Generous default settings
From the moment you first generate a project, configuration files for ESLint, EditorConfig, and even VSCode are added. For VSCode users, Format on Save works without any setup, and both Storybook and Jest are available by default. This instantly silenced the part of me that was complaining about configurations.
Powerful code generation
RedwoodJS is a framework influenced by Ruby on Rails. Much like Rails generators, Redwood features generate and scaffold capabilities.
Since a generate command is available for almost every unit used in Redwood development[3], you can start writing code without having to write boilerplate content. Furthermore, test files and Storybook files are also generated by default at this time. It’s incredibly thorough. It seems to take over the work I used to struggle with using scaffdog or Hygen. The author, who was complaining about configurations... (omitted).
Another great thing about code generation is that the directory structure is clearly defined. By following Redwood's conventions, you can proceed with development while maintaining a good directory structure.
If you just want to create the simplest CRUD operations, simply writing a database schema with Prisma and running the scaffold command will automatically generate everything, even the frontend. I was truly surprised when I saw this in the tutorial.
Easy Form implementation
For form-related functionality, components and hooks that wrap React Hook Form are already provided. Although they are customized (slightly) for Redwood, you can still fully benefit from them in your code.
Type-safe fetching
Since GraphQL is used, both Queries and Mutations are typed. This is very pleasant.
Overall Overview
What kind of structure do "Redwood Way" applications have? Here, I will introduce the main components in the frontend and backend to give you a general idea of the RedwoodJS application structure.
Frontend
The main components in the frontend are:
- Page
- Pages corresponding to URL paths
- Specified in
Routes.tsx
- Layout
- Accepts
childrenand defines the page layout - Specified for pages in
Routes.tsx
- Accepts
- Cell
- A feature specialized for writing asynchronous processes (data fetching)
- (Described later in "Redwood-Specific Points")
- Component
- Regular components
Only the Cell is unique and will be explained later; others should be easy to understand.
Backend
The main components in the backend are:
- Prisma schema
- Definition of the database schema
- services
- GraphQL Resolvers corresponding to SDL
- Business logic, validation, etc.
- Persistence layer access via Prisma
- GraphQL SDL
- Definition of the GraphQL schema
There might be concerns that services has too many responsibilities, but it's not a big deal if you think of it as the MVC pattern used in Rails. GraphQL Resolvers can be seen mostly as Controllers, and you can think of Prisma as ActiveRecord returning table models (though that might be stretching it a bit).
In fact, although it's experimental, RedwoodJS has a feature called RedwoodRecord. It's an ORM built by wrapping Prisma, aiming for an ActiveRecord-like writing style from Rails.
I have discussed Redwood by forcefully comparing it to Rails, but you don't actually need to think of it this way. This is because a Resolver is just a JS function.
The constraints imposed on a Resolver are:
- It must have the same name as the Query or Mutation defined in the SDL (a RedwoodJS constraint).
- It must return the data corresponding to the Query or Mutation (behavior as a Resolver).
(I'll elaborate on this later.) As long as you follow these, there's no problem with splitting the logic into other functions. By using Prisma as just a data access library and breaking down a series of operations into several functions, you can handle even fairly complex logic.[4]
Redwood-Specific Points
While Redwood provides a luxurious development experience by default, it adds unique features and rules to realize the "Redwoods Way" (rather than the Rails Way). Even for those who know React and GraphQL, there are several points you should at least understand. Here, I will introduce points where you can feel Redwood's unique characteristics.
Use Cell for Asynchronous Fetching
Suddenly, a term you've probably never heard before appears. A Cell is a feature provided by RedwoodJS for performing fetching (asynchronous processes).
When you define and export constants with specific names such as QUERY, Loading, Empty, Success, and Failure, Redwood automatically switches components based on the state of the fetching or asynchronous process.
The following is code for a Cell cited from the tutorial, with comments added.
import type { ArticlesQuery } from 'types/graphql'
import type { CellSuccessProps, CellFailureProps } from '@redwoodjs/web'
// GraphQL Query to fetch data used in `Success`
export const QUERY = gql`
query ArticlesQuery {
articles {
id
}
}
`
// Component to display while loading
export const Loading = () => <div>Loading...</div>
// Component to display when the query result is empty
export const Empty = () => <div>Empty</div>
// Component to display when fetching fails
export const Failure = ({ error }: CellFailureProps) => (
<div style={{ color: 'red' }}>Error: {error.message}</div>
)
// Component to display when fetching succeeds
export const Success = ({ articles }: CellSuccessProps<ArticlesQuery>) => {
return (
<ul>
{articles.map((item) => {
return <li key={item.id}>{JSON.stringify(item)}</li>
})}
</ul>
)
}
This is a writing style I've rarely seen—just defining and exporting components.
If you look at the style of defining components separately to write more declaratively instead of using conditional branching within a component, it feels similar to asynchronous processing using Suspense.
Routing is react-router Style
Routing in RedwoodJS is defined in a react-router style rather than File System Routing like Next.js. Here, you specify the mapping between URL paths and pages, as well as page layouts and authentication.
import { Router, Route, Set, Private } from '@redwoodjs/router'
import BlogLayout from 'src/layouts/BlogLayout/BlogLayout'
import ScaffoldLayout from 'src/layouts/ScaffoldLayout'
const Routes = () => {
return (
<Router>
<Route path="/login" page={LoginPage} name="login" />
<Route path="/signup" page={SignupPage} name="signup" />
<Route path="/forgot-password" page={ForgotPasswordPage} name="forgotPassword" />
<Route path="/reset-password" page={ResetPasswordPage} name="resetPassword" />
{/* Pages requiring authentication */}
<Private unauthenticated="home">
<Set wrap={ScaffoldLayout} title="Posts" titleTo="posts" buttonLabel="New Post" buttonTo="newPost">
<Route path="/admin/posts/new" page={PostNewPostPage} name="newPost" />
<Route path="/admin/posts/{id:Int}/edit" page={PostEditPostPage} name="editPost" />
<Route path="/admin/posts/{id:Int}" page={PostPostPage} name="post" />
<Route path="/admin/posts" page={PostPostsPage} name="posts" />
</Set>
</Private>
{/* Pages to apply BlogLayout */}
<Set wrap={BlogLayout}>
<Route path="/article/{id:Int}" page={ArticlePage} name="article" />
<Route path="/contact" page={ContactPage} name="contact" />
<Route path="/about" page={AboutPage} name="about" />
<Route path="/" page={HomePage} name="home" />
</Set>
<Route notfound page={NotFoundPage} />
</Router>
)
}
export default Routes
It uses <Private> to specify pages requiring authentication and <Set> to apply layouts to pages.
Do Not Write GraphQL Resolver Maps
In RedwoodJS, there is no need to write a Resolver Map that maps GraphQL resolvers to the SDL. This is because defined resolvers are automatically mapped to Query or Mutation objects with the same name as defined in the SDL.
export const contacts: QueryResolvers['contacts'] = () => {
return db.contact.findMany()
}
export const contact: QueryResolvers['contact'] = ({ id }) => {
return db.contact.findUnique({
where: { id },
})
}
export const schema = gql`
type Contact {
id: Int!
name: String!
email: String!
message: String!
createdAt: DateTime!
}
type Query {
contacts: [Contact!]! @requireAuth
contact(id: Int!): Contact @requireAuth
}
`
Summary
Redwood is a framework that not only includes all the convenient tools around React but also makes connecting to the persistence layer extremely convenient. Furthermore, by intentionally being bound by the "Redwoods Way" conventions, you can achieve efficient development. While these characteristics may leave room for consideration before being adopted for production code that requires long-term maintenance, wouldn't you agree that they are effective in many cases for short-lived projects, such as prototypes, that are intended to be discarded once verification is complete?
If you are a developer who regularly writes React and is familiar with GraphQL and Prisma, you can start developing with almost no learning cost. If you have the chance to write a full-stack web app using React, please give it a try.
Redwood is still a framework with few Japanese articles, so I hope this article will spark interest and lead more people to use it.
Related Information
Getting Started with RedwoodJS
If you're interested in getting started with RedwoodJS after reading this article, please check out the official tutorial. It's very easy to follow and learn from.
Japanese Articles on RedwoodJS
Discussion