In the previous tutorial, we finished our Home Page, so we will build out our Sign In and Sign Up Pages and hook up the logic to allow us to sign in and sign up.
Let's start by creating our routes.
Next, we can group our routes and create shared layouts; you can read more here, but for our use case, we will create a route group called auth
, to make a route a group, you will create a folder whose name will be between parentheses.
Our folder structure will look like the following.
(auth)
(auth)
folder, create two additional folders, signin
and signup
, with a blank page.tsx
file.(auth)
folder, create a file called layout.tsx
to function as our shared layout between our signin
and signup
pages.You can learn more about the layout.tsx
file in Next.js docs here
Now that we have our basic folder structure. Let's create the following components.
In the layout.tsx
file, paste the following code.
1export default function AuthLayout({ children }: {
2 readonly children: React.ReactNode;
3}) {
4 return (
5 <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
6 {children}
7 </div>
8 );
9}
Paste the following code in the signin/page.tsx
file.
1export default function SignInRoute() {
2 return <div>Sign In Route</div>;
3}
Paste the following code in the signup/page.tsx
file.
1export default function SingUpRoute() {
2 return <div>Sign Up Route</div>;
3}
After creating the following components you should be able to navigate to our signin
page via the link.
Inside src/app
, create the following.
Great. Let's now work on our signin
and signup
forms.
Let's navigate to app/components
and create a new folder called forms
. Inside that folder, create two new files called signin-form.tsx
and signup-form.tsx
and paste the following code for the respective components.
signin-form.tsx
1"use client";
2
3import Link from "next/link";
4
5import {
6 CardTitle,
7 CardDescription,
8 CardHeader,
9 CardContent,
10 CardFooter,
11 Card,
12} from "@/components/ui/card";
13
14import { Label } from "@/components/ui/label";
15import { Input } from "@/components/ui/input";
16
17export function SigninForm() {
18 return (
19 <div className="w-full max-w-md">
20 <form>
21 <Card>
22 <CardHeader className="space-y-1">
23 <CardTitle className="text-3xl font-bold">Sign In</CardTitle>
24 <CardDescription>
25 Enter your details to sign in to your account
26 </CardDescription>
27 </CardHeader>
28 <CardContent className="space-y-4">
29 <div className="space-y-2">
30 <Label htmlFor="email">Email</Label>
31 <Input
32 id="identifier"
33 name="identifier"
34 type="text"
35 placeholder="username or email"
36 />
37 </div>
38 <div className="space-y-2">
39 <Label htmlFor="password">Password</Label>
40 <Input
41 id="password"
42 name="password"
43 type="password"
44 placeholder="password"
45 />
46 </div>
47 </CardContent>
48 <CardFooter className="flex flex-col">
49 <button className="w-full">Sign In</button>
50 </CardFooter>
51 </Card>
52 <div className="mt-4 text-center text-sm">
53 Don't have an account?
54 <Link className="underline ml-2" href="signup">
55 Sign Up
56 </Link>
57 </div>
58 </form>
59 </div>
60 );
61}
signup-form.tsx
1"use client";
2
3import Link from "next/link";
4
5import {
6 CardTitle,
7 CardDescription,
8 CardHeader,
9 CardContent,
10 CardFooter,
11 Card,
12} from "@/components/ui/card";
13
14import { Label } from "@/components/ui/label";
15import { Input } from "@/components/ui/input";
16
17export function SignupForm() {
18 return (
19 <div className="w-full max-w-md">
20 <form>
21 <Card>
22 <CardHeader className="space-y-1">
23 <CardTitle className="text-3xl font-bold">Sign Up</CardTitle>
24 <CardDescription>
25 Enter your details to create a new account
26 </CardDescription>
27 </CardHeader>
28 <CardContent className="space-y-4">
29 <div className="space-y-2">
30 <Label htmlFor="username">Username</Label>
31 <Input
32 id="username"
33 name="username"
34 type="text"
35 placeholder="username"
36 />
37 </div>
38 <div className="space-y-2">
39 <Label htmlFor="email">Email</Label>
40 <Input
41 id="email"
42 name="email"
43 type="email"
44 placeholder="name@example.com"
45 />
46 </div>
47
48 <div className="space-y-2">
49 <Label htmlFor="password">Password</Label>
50 <Input
51 id="password"
52 name="password"
53 type="password"
54 placeholder="password"
55 />
56 </div>
57 </CardContent>
58 <CardFooter className="flex flex-col">
59 <button className="w-full">Sign Up</button>
60 </CardFooter>
61 </Card>
62 <div className="mt-4 text-center text-sm">
63 Have an account?
64 <Link className="underline ml-2" href="signin">
65 Sing In
66 </Link>
67 </div>
68 </form>
69 </div>
70 );
71}
Since we are using Shadcn UI, we need to install the card
, input
, and label
components since we are using them in the code above.
You can learn more about Shadcn UI here
We can install the components by running the following code.
npx shadcn@latest add card label input
Now that we have installed our components, let's navigate to app/(auth)/signin/page.tsx
and import and add our newly created SigninForm
component.
The final code should look like the following.
1import { SigninForm } from "@/components/forms/signin-form";
2
3export default function SingInRoute() {
4 return <SigninForm />;
5}
Let's do the same inside the signup/page.tsx
file by updating the following.
1import { SignupForm } from "@/components/forms/signup-form";
2
3export default function SingUoRoute() {
4 return <SignupForm />;
5}
Now restart your frontend Next.js application. You should see the following when navigating the Sign In page.
Nice, we now have both of our forms. Before getting into the details of how to implement our form submission via Server Actions, here are some great resources to learn more about the process MDN HTML Forms and specific to Next.js Server Action & Mutations
Now let's dive in in building out our SignupForm
.
We will first focus on our SignupForm
, and then, after we understand how things work, we will make the same changes inside our SigninForm
.
While building our form, let's consider these items in the context of Next.js.
name
attribute in the input
fields inside the form.button
with the submit, it will submit the form and trigger our action.Let's start by defining our first Next.js server actions. Navigate to src/app/data
and create a new folder called actions
and a file name auth-actions.ts
.
Inside our newly created file, let's paste the following code.
1"use server";
2
3export async function registerUserAction(formData: FormData) {
4 console.log("Hello From Register User Action");
5}
Now let's import our registerUserAction
inside our signup-form.tsx
file and add it to our form action.
1import { registerUserAction } from "@/data/actions/auth-actions";
Update the form attribute with the following:
1{
2 /* rest of our code */
3}
4<form action={registerUserAction}>
5{/* rest of our code */}
6</form>;
7{
8 /* rest of our code */
9}
Now, you should be able to click the Sign Up
button, and we should see our console log in our terminal since it is being executed on the server.
Nice. We don't know if we can trigger our server action
via our form submission. Let's examine how we can access our form data via our FormData.
For additional reading, I recommend checking out this post about FormData on MDN, but we will be using the get
method to get our values.
When we submit our form, the values will be passed down to our server action via the form data using the input name
attribute as the key to our value.
For example, we can retrieve our data using FormData.get("username")
for the following input.
With the following code, let's update our registerUserAction
action in the auth-actions.ts
file.
1"use server";
2
3export async function registerUserAction(formData: FormData) {
4 console.log("Hello From Register User Action");
5
6 const fields = {
7 username: formData.get("username"),
8 password: formData.get("password"),
9 email: formData.get("email"),
10 };
11
12 console.log("#############");
13 console.log(fields);
14 console.log("#############");
15}
Now, fill out the fields in the Signup form and click the Sign Up button. You should see the following console log in your terminal.
Hello From Register User Action
#############
{
username: 'testuser',
password: 'Monkey1234!',
email: 'testuser@email.com'
}
#############
We can now get our data in our server action
, but how do we return or validate it?
Well, that is what we will do in our next section.
We will use React's useActionState
hook to return data from our server action
. You can learn more here.
Let's first start in the signup-form.tsx
file.
We will first import our useActionState
hook from react-dom
.
1import { useActionState } from "react";
Now, let's create a variable to store our initial state.
1const INITIAL_STATE = {
2 data: null,
3};
Now let's use our useActionState
hook.
1const [formState, formAction] = useActionState(registerUserAction, INITIAL_STATE);
And update the form
action attribute with the following.
1 <form action={formAction}>
The completed code should look like the following.
1"use client";
2
3import Link from "next/link";
4import { useActionState } from "react";
5
6import { registerUserAction } from "@/data/actions/auth-actions";
7
8import {
9 CardTitle,
10 CardDescription,
11 CardHeader,
12 CardContent,
13 CardFooter,
14 Card,
15} from "@/components/ui/card";
16
17import { Label } from "@/components/ui/label";
18import { Input } from "@/components/ui/input";
19
20const INITIAL_STATE = {
21 data: null,
22};
23
24export function SignupForm() {
25 const [formState, formAction] = useActionState(registerUserAction, INITIAL_STATE);
26
27 console.log("## will render on client ##");
28 console.log(formState);
29 console.log("###########################");
30
31 return (
32 <div className="w-full max-w-md">
33 <form action={formAction}>
34 <Card>
35 <CardHeader className="space-y-1">
36 <CardTitle className="text-3xl font-bold">Sign Up</CardTitle>
37 <CardDescription>
38 Enter your details to create a new account
39 </CardDescription>
40 </CardHeader>
41 <CardContent className="space-y-4">
42 <div className="space-y-2">
43 <Label htmlFor="username">Username</Label>
44 <Input
45 id="username"
46 name="username"
47 type="text"
48 placeholder="username"
49 />
50 </div>
51 <div className="space-y-2">
52 <Label htmlFor="email">Email</Label>
53 <Input
54 id="email"
55 name="email"
56 type="email"
57 placeholder="name@example.com"
58 />
59 </div>
60
61 <div className="space-y-2">
62 <Label htmlFor="password">Password</Label>
63 <Input
64 id="password"
65 name="password"
66 type="password"
67 placeholder="password"
68 />
69 </div>
70 </CardContent>
71 <CardFooter className="flex flex-col">
72 <button className="w-full">Sign Up</button>
73 </CardFooter>
74 </Card>
75 <div className="mt-4 text-center text-sm">
76 Have an account?
77 <Link className="underline ml-2" href="signin">
78 Sing In
79 </Link>
80 </div>
81 </form>
82 </div>
83 );
84}
Finally, we have to update our registerUserAction
action in the auth-actions.ts
file using the following code:
1"use server";
2
3export async function registerUserAction(prevState: any, formData: FormData) {
4 console.log("Hello From Register User Action");
5
6 const fields = {
7 username: formData.get("username"),
8 password: formData.get("password"),
9 email: formData.get("email"),
10 };
11
12 console.log(fields);
13
14 return {
15 ...prevState,
16 data: fields,
17 };
18}
When you submit the form, you should see our data console logged in our frontend via our console.log(formState);
that we have in our signup-form.tsx
file.
This is great. We are able to pass data to our server action
and return it via useActionState
.
Before we see how to submit our form and sign in via our Strapi backend, let's examine how to handle form validation with Zod.
You can learn more about Zod on their website here.
Zod is a validation library designed for use with TypeScript and JavaScript.
It offers an expressive syntax for creating complex validation schema, which makes Zod particularly useful for validating user-generated data, such as information submitted through forms or received from API requests, to ensure the data aligns with your application's expected structures and types.
Let's examine how we can add Zod validation for our forms. We will choose to do the validation inside of our server action
.
Let's start by installing Zod with the following command.
yarn add zod
Once the installation is complete, restart your app, navigate to our auth-actions.ts
file, and import it with the following command.
1import { z } from "zod";
Next, let's define our schema. You can learn more about Zod schemas here.
1const schemaRegister = z.object({
2 username: z.string().min(3).max(20, {
3 message: "Username must be between 3 and 20 characters",
4 }),
5 password: z.string().min(6).max(100, {
6 message: "Password must be between 6 and 100 characters",
7 }),
8 email: z.string().email({
9 message: "Please enter a valid email address",
10 }),
11});
Here, we are adding simple validation and message.
Now, let's update our registerUserAction
to use our schema to validate our fields by making the following changes.
1export async function registerUserAction(prevState: any, formData: FormData) {
2 console.log("Hello From Register User Action");
3
4 const validatedFields = schemaRegister.safeParse({
5 username: formData.get("username"),
6 password: formData.get("password"),
7 email: formData.get("email"),
8 });
9
10 if (!validatedFields.success) {
11 return {
12 ...prevState,
13 zodErrors: validatedFields.error.flatten().fieldErrors,
14 strapiErrors: null,
15 message: "Missing Fields. Failed to Register.",
16 };
17 }
18
19 return {
20 ...prevState,
21 data: "ok",
22 };
23}
We are using Zod in the above code to validate our user registration data.
The schemaRegister.safeParse
function validates username, password, and email fields extracted from formData.
If validation fails (indicated by validatedFields.success being false), the function returns the previous state, Zod validation errors (zodErrors), and a failure message.
If validation succeeds, it returns the previous state updated with a success indicator.
This Zod validation process ensures that user data meets the application's requirements before proceeding.
Let's test our form by not adding any of our fields and submitting it.
Notice we can see our errors in the front end. Let's create a new component called ZodErrors
to help us display them inside our signup-form.tsx
file.
First, navigate to src/app/components/custom
, create a new file called zod-errors.tsx
, and paste it into the following code.
1export function ZodErrors({ error }: { error: string[] }) {
2 if (!error) return null;
3 return error.map((err: string, index: number) => (
4 <div key={index} className="text-pink-500 text-xs italic mt-1 py-2">
5 {err}
6 </div>
7 ));
8}
Now, navigate to src/app/components/forms/signup-form.tsx
and let's use the following component.
We will import and add it to our form and pass the zod errors we are getting back from our formState
.
The updated signup-form.tsx
code should look like the following.
1"use client";
2
3import Link from "next/link";
4import { useActionState } from "react";
5import { registerUserAction } from "@/data/actions/auth-actions";
6
7import {
8 CardTitle,
9 CardDescription,
10 CardHeader,
11 CardContent,
12 CardFooter,
13 Card,
14} from "@/components/ui/card";
15
16import { Label } from "@/components/ui/label";
17import { Input } from "@/components/ui/input";
18
19import { ZodErrors } from "@/components/custom/zod-errors";
20
21const INITIAL_STATE = {
22 data: null,
23};
24
25export function SignupForm() {
26 const [formState, formAction] = useActionState(
27 registerUserAction,
28 INITIAL_STATE
29 );
30
31 console.log("## will render on client ##");
32 console.log(formState);
33 console.log("###########################");
34
35 return (
36 <div className="w-full max-w-md">
37 <form action={formAction}>
38 <Card>
39 <CardHeader className="space-y-1">
40 <CardTitle className="text-3xl font-bold">Sign Up</CardTitle>
41 <CardDescription>
42 Enter your details to create a new account
43 </CardDescription>
44 </CardHeader>
45 <CardContent className="space-y-4">
46 <div className="space-y-2">
47 <Label htmlFor="username">Username</Label>
48 <Input
49 id="username"
50 name="username"
51 type="text"
52 placeholder="username"
53 />
54 <ZodErrors error={formState?.zodErrors?.username} />
55 </div>
56 <div className="space-y-2">
57 <Label htmlFor="email">Email</Label>
58 <Input
59 id="email"
60 name="email"
61 type="email"
62 placeholder="name@example.com"
63 />
64 <ZodErrors error={formState?.zodErrors?.email} />
65 </div>
66
67 <div className="space-y-2">
68 <Label htmlFor="password">Password</Label>
69 <Input
70 id="password"
71 name="password"
72 type="password"
73 placeholder="password"
74 />
75 <ZodErrors error={formState?.zodErrors?.password} />
76 </div>
77 </CardContent>
78 <CardFooter className="flex flex-col">
79 <button className="w-full">Sign Up</button>
80 </CardFooter>
81 </Card>
82 <div className="mt-4 text-center text-sm">
83 Have an account?
84 <Link className="underline ml-2" href="signin">
85 Sing In
86 </Link>
87 </div>
88 </form>
89 </div>
90 );
91}
Now, restart your frontend Next.js project and try submitting the form without entering any data; you should see the following errors.
Nice. We don't know if our form validation works, so let's move on and create a service that will handle our Strapi Auth Login.
Now, let's implement Strapi authentication by registering our user via our Strapi API. You can find the process explained here
The basic overview,
httpOnly
cookiedashboard
.Let's start by creating a service that will handle Strapi User Registration.
Navigate to src/app/data
and create a new folder called services
inside. Create the file auth-service.ts
and paste it into the following code.
1import { getStrapiURL } from "@/lib/utils";
2
3interface RegisterUserProps {
4 username: string;
5 password: string;
6 email: string;
7}
8
9interface LoginUserProps {
10 identifier: string;
11 password: string;
12}
13
14const baseUrl = getStrapiURL();
15
16export async function registerUserService(userData: RegisterUserProps) {
17 const url = new URL("/api/auth/local/register", baseUrl);
18
19 try {
20 const response = await fetch(url, {
21 method: "POST",
22 headers: {
23 "Content-Type": "application/json",
24 },
25 body: JSON.stringify({ ...userData }),
26 });
27
28 return response.json();
29 } catch (error) {
30 console.error("Registration Service Error:", error);
31 }
32}
33
34export async function loginUserService(userData: LoginUserProps) {
35 const url = new URL("/api/auth/local", baseUrl);
36
37 try {
38 const response = await fetch(url, {
39 method: "POST",
40 headers: {
41 "Content-Type": "application/json",
42 },
43 body: JSON.stringify({ ...userData }),
44 });
45
46 return response.json();
47 } catch (error) {
48 console.error("Login Service Error:", error);
49 throw error;
50 }
51}
This includes both our registerUserService
and loginUserService
, which is based on what you can find in the Strapi Docs here.
Now, we can utilize our registerUserService
service inside our auth-actions.ts
file. Let's navigate to that file and add the following to our registerUserAction
.
1const responseData = await registerUserService(validatedFields.data);
2
3if (!responseData) {
4 return {
5 ...prevState,
6 strapiErrors: null,
7 zodErrors: null,
8 message: "Ops! Something went wrong. Please try again.",
9 };
10}
11
12if (responseData.error) {
13 return {
14 ...prevState,
15 strapiErrors: responseData.error,
16 zodErrors: null,
17 message: "Failed to Register.",
18 };
19}
Don't forget to import our registerUserService
with the following.
1import { registerUserService } from "@/data/services/auth-service";
The completed code should look like the following.
1"use server";
2import { z } from "zod";
3import { registerUserService } from "@/data/services/auth-service";
4
5const schemaRegister = z.object({
6 username: z.string().min(3).max(20, {
7 message: "Username must be between 3 and 20 characters",
8 }),
9 password: z.string().min(6).max(100, {
10 message: "Password must be between 6 and 100 characters",
11 }),
12 email: z.string().email({
13 message: "Please enter a valid email address",
14 }),
15});
16
17export async function registerUserAction(prevState: any, formData: FormData) {
18 console.log("Hello From Register User Action");
19
20 const validatedFields = schemaRegister.safeParse({
21 username: formData.get("username"),
22 password: formData.get("password"),
23 email: formData.get("email"),
24 });
25
26 if (!validatedFields.success) {
27 return {
28 ...prevState,
29 zodErrors: validatedFields.error.flatten().fieldErrors,
30 strapiErrors: null,
31 message: "Missing Fields. Failed to Register.",
32 };
33 }
34
35 const responseData = await registerUserService(validatedFields.data);
36
37 if (!responseData) {
38 return {
39 ...prevState,
40 strapiErrors: null,
41 zodErrors: null,
42 message: "Ops! Something went wrong. Please try again.",
43 };
44 }
45
46 if (responseData.error) {
47 return {
48 ...prevState,
49 strapiErrors: responseData.error,
50 zodErrors: null,
51 message: "Failed to Register.",
52 };
53 }
54
55 console.log("#############");
56 console.log("User Registered Successfully", responseData.jwt);
57 console.log("#############");
58}
Notice in the code above, inside of our return we are now returning strapiErrors
. We will see how to render them in the front in just a moment, but first, let's test our form and see if we can see our jwt
token being returned in our terminal console.
Nice, we are able to create a new user and register. Before moving on to handling redirects and setting the httpOnly
cookie, let's create a component to render our Strapi Errors and Make our Submit Button cooler.
Now that we have implemented Next.js Strapi authentication, let's ensure that we handle some Strapi errors. Navigate to src/app/components/custom
, create a new file named strapi-errors.tsx
, and paste the following code.
1interface StrapiErrorsProps {
2 message: string | null;
3 name: string;
4 status: string | null;
5}
6
7export function StrapiErrors( { error }: { readonly error: StrapiErrorsProps }) {
8 if (!error?.message) return null;
9 return <div className="text-pink-500 text-md italic py-2">{error.message}</div>;
10}
Now navigate back to our signup-form.tsx
file, import our newly created component, and add it right after our' submit' button.
1import { StrapiErrors } from "@/components/custom/strapi-errors";
1<CardFooter className="flex flex-col">
2 <button className="w-full">Sign Up</button>
3 <StrapiErrors error={formState?.strapiErrors} />
4</CardFooter>
Let's test and see if we can see our Strapi Errors. Try creating another user with an email you used to make your first user.
You should see the following message.
Let's improve our submit
button by adding a pending state and making it prettier.
When we submit a form, it may be in a pending state, and we would like to show a spinner for a better user experience.
Let's look at how we can accomplish this by creating a SubmitButton
component that will utilize the useFormStatus
hook. The Next.js docs provide more details here.
The useFormStatus
Hook gives you the status information of the last form submission. We will use that to get the status of our form and show our loading spinner.
Let's start by navigating to app/components/custom
, creating the following file name submit-button.tsx
, and adding the following code.
1"use client";
2import { useFormStatus } from "react-dom";
3import { cn } from "@/lib/utils";
4import { Button } from "@/components/ui/button";
5import { Loader2 } from "lucide-react";
6
7function Loader({ text }: { readonly text: string }) {
8 return (
9 <div className="flex items-center space-x-2">
10 <Loader2 className="mr-2 h-4 w-4 animate-spin" />
11 <p>{text}</p>
12 </div>
13 );
14}
15
16interface SubmitButtonProps {
17 text: string;
18 loadingText: string;
19 className?: string;
20 loading?: boolean;
21}
22
23export function SubmitButton({
24 text,
25 loadingText,
26 loading,
27 className,
28}: Readonly<SubmitButtonProps>) {
29 const status = useFormStatus();
30 return (
31 <Button
32 type="submit"
33 aria-disabled={status.pending || loading}
34 disabled={status.pending || loading}
35 className={cn(className)}
36 >
37 {status.pending || loading ? <Loader text={loadingText} /> : text}
38 </Button>
39 );
40}
Now that we have our new SubmitButton component, let's use it inside our signup-form.tsx
file.
Let's replace our boring button
with the following, but first, ensure you import it.
1import { SubmitButton } from "@/components/custom/submit-button";
Inside our CardFooter
, let's update you with the following:
1<CardFooter className="flex flex-col">
2 <SubmitButton className="w-full" text="Sign Up" loadingText="Loading" />
3 <StrapiErrors error={formState?.strapiErrors} />
4</CardFooter>
Now let's test our new beautiful button.
It's beautiful.
The last two things we need to do are to look at how to set our JWT token as a httpOnly
cookie, handle redirects, and set up protected routes with the middleware.ts
file.
We will add this logic to our auth-actions.ts
file and our registerUserAction
function.
You can learn more about setting cookies in Next.js on their docs here
Let's make the following change inside of our registerUserAction
file.
First import cookies
from Next:
1import { cookies } from "next/headers";
Next, create a variable to store our cookies
config.
1const config = {
2 maxAge: 60 * 60 * 24 * 7, // 1 week
3 path: "/",
4 domain: process.env.HOST ?? "localhost",
5 httpOnly: true,
6 secure: process.env.NODE_ENV === "production",
7};
Finally, use the following code to set the cookie.
1 const cookieStore = await cookies();
2 cookieStore.set("jwt", responseData.jwt, config);
Finally, let's add a redirect to our dashboard
; first, we must create the page, so let's do that now.
The final code should look like the following. Notice we are using the redirect
function from Next.js to redirect the user to the dashboard
page; you can learn more here.
1"use server";
2import { z } from "zod";
3import { cookies } from "next/headers";
4import { redirect } from "next/navigation";
5
6import { registerUserService } from "@/data/services/auth-service";
7
8const config = {
9 maxAge: 60 * 60 * 24 * 7, // 1 week
10 path: "/",
11 domain: process.env.HOST ?? "localhost",
12 httpOnly: true,
13 secure: process.env.NODE_ENV === "production",
14};
15
16const schemaRegister = z.object({
17 username: z.string().min(3).max(20, {
18 message: "Username must be between 3 and 20 characters",
19 }),
20 password: z.string().min(6).max(100, {
21 message: "Password must be between 6 and 100 characters",
22 }),
23 email: z.string().email({
24 message: "Please enter a valid email address",
25 }),
26});
27
28export async function registerUserAction(prevState: any, formData: FormData) {
29 const validatedFields = schemaRegister.safeParse({
30 username: formData.get("username"),
31 password: formData.get("password"),
32 email: formData.get("email"),
33 });
34
35 if (!validatedFields.success) {
36 return {
37 ...prevState,
38 zodErrors: validatedFields.error.flatten().fieldErrors,
39 strapiErrors: null,
40 message: "Missing Fields. Failed to Register.",
41 };
42 }
43
44 const responseData = await registerUserService(validatedFields.data);
45
46 if (!responseData) {
47 return {
48 ...prevState,
49 strapiErrors: null,
50 zodErrors: null,
51 message: "Ops! Something went wrong. Please try again.",
52 };
53 }
54
55 if (responseData.error) {
56 return {
57 ...prevState,
58 strapiErrors: responseData.error,
59 zodErrors: null,
60 message: "Failed to Register.",
61 };
62 }
63
64 const cookieStore = await cookies();
65 cookieStore.set("jwt", responseData.jwt, config);
66
67 redirect("/dashboard");
68}
Inside the app
folder, create the dashboard
folder with a page.tsx
file containing the following code.
1export default function DashboardRoute() {
2 return (
3 <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
4 <h1>Dashboard</h1>
5 </div>
6 );
7}
Let's create another user and see our redirect in action and our cookies set.
You can see here that we are saving it as an httpOnly
cookie.
Nice. We are almost done with the authentication flow, but we still have a small issue. If I remove the cookie, we are still able to navigate to the dashboard,
but that should be a protected route.
We will use Next.js middleware
to protect our routes. You can learn more here.
In the src
folder, create a file called middleware.ts
and paste it into the following code.
1import { NextResponse } from "next/server";
2import type { NextRequest } from "next/server";
3import { getUserMeLoader } from "@/data/services/get-user-me-loader";
4
5// Define an array of protected routes
6const protectedRoutes = [
7 "/dashboard",
8 // Add more protected routes here
9];
10
11// Helper function to check if a path is protected
12function isProtectedRoute(path: string): boolean {
13 return protectedRoutes.some((route) => path.startsWith(route));
14}
15
16export async function middleware(request: NextRequest) {
17 const user = await getUserMeLoader();
18 const currentPath = request.nextUrl.pathname;
19
20 if (isProtectedRoute(currentPath) && user.ok === false) {
21 return NextResponse.redirect(new URL("/signin", request.url));
22 }
23
24 return NextResponse.next();
25}
26
27// Optionally, you can add a matcher to optimize performance
28export const config = {
29 matcher: [
30 /*
31 * Match all request paths except for the ones starting with:
32 * - api (API routes)
33 * - _next/static (static files)
34 * - _next/image (image optimization files)
35 * - favicon.ico (favicon file)
36 */
37 "/((?!api|_next/static|_next/image|favicon.ico).*)",
38 ],
39};
In the code above, we are using the getUserMeLoader
function, which we will create in just a minute, to call our Strapi API to see if the user is still logged in.
If so, we will have the user's information. If the user information does not exist, we will redirect the user to the signin page.
Now, navigate to our services
folder and create the following files.
First, let's create a helpful function to get our JWT
token.
Create a file inside the services
folder called get-token.ts
and add the following code.
1import { cookies } from "next/headers";
2
3export async function getAuthToken() {
4 const cookieStore = await cookies();
5 const authToken = cookieStore.get("jwt")?.value;
6 return authToken;
7}
Create another file called get-user-me-loader.ts
and paste it into the following code.
1import { getAuthToken } from "./get-token";
2import { getStrapiURL } from "@/lib/utils";
3
4export async function getUserMeLoader() {
5 const baseUrl = getStrapiURL();
6
7 const url = new URL("/api/users/me", baseUrl);
8
9 const authToken = await getAuthToken();
10 if (!authToken) return { ok: false, data: null, error: null };
11
12 try {
13 const response = await fetch(url.href, {
14 method: "GET",
15 headers: {
16 "Content-Type": "application/json",
17 Authorization: `Bearer ${authToken}`,
18 },
19 });
20 const data = await response.json();
21 if (data.error) return { ok: false, data: null, error: data.error };
22 return { ok: true, data: data, error: null };
23 } catch (error) {
24 console.log(error);
25 return { ok: false, data: null, error: error };
26 }
27}
Now, restart your application, delete your previous cookie, and try to navigate to dashboard
. We will be redirected back to the `sign-in page.
Nice. Now that we know our middleware
is working, let's make the updates in our SigninForm
instead of going step by step like we did. Since we will basically do the same thing we did in the SignupForm,
we are just going to paste in the completed code.
Let's start in the auth-actions.ts
file and replace it with the following code.
1"use server";
2import { z } from "zod";
3import { cookies } from "next/headers";
4import { redirect } from "next/navigation";
5
6import {
7 registerUserService,
8 loginUserService,
9} from "@/data/services/auth-service";
10
11const config = {
12 maxAge: 60 * 60 * 24 * 7, // 1 week
13 path: "/",
14 domain: process.env.HOST ?? "localhost",
15 httpOnly: true,
16 secure: process.env.NODE_ENV === "production",
17};
18
19const schemaRegister = z.object({
20 username: z.string().min(3).max(20, {
21 message: "Username must be between 3 and 20 characters",
22 }),
23 password: z.string().min(6).max(100, {
24 message: "Password must be between 6 and 100 characters",
25 }),
26 email: z.string().email({
27 message: "Please enter a valid email address",
28 }),
29});
30
31export async function registerUserAction(prevState: any, formData: FormData) {
32 const validatedFields = schemaRegister.safeParse({
33 username: formData.get("username"),
34 password: formData.get("password"),
35 email: formData.get("email"),
36 });
37
38 if (!validatedFields.success) {
39 return {
40 ...prevState,
41 zodErrors: validatedFields.error.flatten().fieldErrors,
42 strapiErrors: null,
43 message: "Missing Fields. Failed to Register.",
44 };
45 }
46
47 const responseData = await registerUserService(validatedFields.data);
48
49 if (!responseData) {
50 return {
51 ...prevState,
52 strapiErrors: null,
53 zodErrors: null,
54 message: "Ops! Something went wrong. Please try again.",
55 };
56 }
57
58 if (responseData.error) {
59 return {
60 ...prevState,
61 strapiErrors: responseData.error,
62 zodErrors: null,
63 message: "Failed to Register.",
64 };
65 }
66
67 const cookieStore = await cookies();
68 cookieStore.set("jwt", responseData.jwt, config);
69
70 redirect("/dashboard");
71}
72
73const schemaLogin = z.object({
74 identifier: z
75 .string()
76 .min(3, {
77 message: "Identifier must have at least 3 or more characters",
78 })
79 .max(20, {
80 message: "Please enter a valid username or email address",
81 }),
82 password: z
83 .string()
84 .min(6, {
85 message: "Password must have at least 6 or more characters",
86 })
87 .max(100, {
88 message: "Password must be between 6 and 100 characters",
89 }),
90});
91
92export async function loginUserAction(prevState: any, formData: FormData) {
93 const validatedFields = schemaLogin.safeParse({
94 identifier: formData.get("identifier"),
95 password: formData.get("password"),
96 });
97
98 if (!validatedFields.success) {
99 return {
100 ...prevState,
101 zodErrors: validatedFields.error.flatten().fieldErrors,
102 message: "Missing Fields. Failed to Login.",
103 };
104 }
105
106 const responseData = await loginUserService(validatedFields.data);
107
108 if (!responseData) {
109 return {
110 ...prevState,
111 strapiErrors: responseData.error,
112 zodErrors: null,
113 message: "Ops! Something went wrong. Please try again.",
114 };
115 }
116
117 if (responseData.error) {
118 return {
119 ...prevState,
120 strapiErrors: responseData.error,
121 zodErrors: null,
122 message: "Failed to Login.",
123 };
124 }
125
126 console.log(responseData, "responseData");
127
128 const cookieStore = await cookies();
129 cookieStore.set("jwt", responseData.jwt, config);
130
131 redirect("/dashboard");
132}
133
134export async function logoutAction() {
135 const cookieStore = await cookies();
136 cookieStore.set("jwt", "", { ...config, maxAge: 0 });
137 redirect("/");
138}
Next, navigate to our signin-form.tsx
file and paste the following code.
1"use client";
2
3import Link from "next/link";
4import { useActionState } from "react";
5import { loginUserAction } from "@/data/actions/auth-actions";
6
7import {
8 CardTitle,
9 CardDescription,
10 CardHeader,
11 CardContent,
12 CardFooter,
13 Card,
14} from "@/components/ui/card";
15
16import { Label } from "@/components/ui/label";
17import { Input } from "@/components/ui/input";
18import { ZodErrors } from "@/components/custom/zod-errors";
19import { StrapiErrors } from "@/components/custom/strapi-errors";
20import { SubmitButton } from "@/components/custom/submit-button";
21
22const INITIAL_STATE = {
23 zodErrors: null,
24 strapiErrors: null,
25 data: null,
26 message: null,
27};
28
29export function SigninForm() {
30 const [formState, formAction] = useActionState(loginUserAction, INITIAL_STATE);
31 return (
32 <div className="w-full max-w-md">
33 <form action={formAction}>
34 <Card>
35 <CardHeader className="space-y-1">
36 <CardTitle className="text-3xl font-bold">Sign In</CardTitle>
37 <CardDescription>
38 Enter your details to sign in to your account
39 </CardDescription>
40 </CardHeader>
41 <CardContent className="space-y-4">
42 <div className="space-y-2">
43 <Label htmlFor="email">Email</Label>
44 <Input
45 id="identifier"
46 name="identifier"
47 type="text"
48 placeholder="username or email"
49 />
50 <ZodErrors error={formState?.zodErrors?.identifier} />
51 </div>
52 <div className="space-y-2">
53 <Label htmlFor="password">Password</Label>
54 <Input
55 id="password"
56 name="password"
57 type="password"
58 placeholder="password"
59 />
60 <ZodErrors error={formState?.zodErrors?.password} />
61 </div>
62 </CardContent>
63 <CardFooter className="flex flex-col">
64 <SubmitButton
65 className="w-full"
66 text="Sign In"
67 loadingText="Loading"
68 />
69 <StrapiErrors error={formState?.strapiErrors} />
70 </CardFooter>
71 </Card>
72 <div className="mt-4 text-center text-sm">
73 Don't have an account?
74 <Link className="underline ml-2" href="signup">
75 Sign Up
76 </Link>
77 </div>
78 </form>
79 </div>
80 );
81}
Finally, let's create a Logout Button. Navigate to app/components/custom
, create a file called logout-button.tsx
and add the following code.
1import { logoutAction } from "@/data/actions/auth-actions";
2import { LogOut } from "lucide-react";
3
4export function LogoutButton() {
5 return (
6 <form action={logoutAction}>
7 <button type="submit">
8 <LogOut className="w-6 h-6 hover:text-primary" />
9 </button>
10 </form>
11 );
12}
Finally, let's import this button into our app/dashboard/page.tsx
file for now.
The code should look like the following.
1import { LogoutButton } from "@/components/custom/logout-button";
2
3export default function DashboardRoute() {
4 return (
5 <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
6 <h1>Dashboard</h1>
7 <LogoutButton />
8 </div>
9 );
10}
Only some things are in place, so let's test our Sign In page.
Nice. Great job.
Protect your application from common threats by following these best practices:
To ensure your application adheres to industry standards, consider reviewing the Strapi security best practices, which include essential measures such as using the latest stable versions, adding HTTPS and SSL certificates, using strong passwords, taking regular backups, securing web hosts, modifying default settings, and installing security plugins.
By implementing these security measures and following best practices, you'll improve the resilience of your Next.js application against potential threats.
Implementing authentication requires thorough testing to ensure your application is secure and functions correctly.
Writing unit tests for your authentication logic helps catch errors early. Using testing frameworks like Jest, you can create tests for your login and signup API routes. For example, you might test that:
By simulating API calls and checking responses, you can verify that your authentication system handles different scenarios as expected.
When issues arise, common problems include misconfigured middleware, incorrect token handling, or server-side errors. To debug effectively:
By systematically checking each part of your authentication flow, you can identify and fix issues to maintain a secure application.
Preparing your Next.js 14 application for deployment involves ensuring that your server settings are properly configured for security and performance.
To secure your application in production, configure your server appropriately:
By carefully configuring your server settings, you improve the security and reliability of your deployed application.
By securing your Next.js 14 application with strong authentication, you've improved your web app's security and user experience. For more performance and flexibility, consider integrating with Strapi's headless CMS solutions.
Strapi offers headless CMS solutions that enhance performance and flexibility, catering to various business needs. These solutions integrate with any frontend framework and allow content to be published across multiple channels simultaneously, improving site performance, scalability, and providing a personalized experience.
In this Next.js tutorial, we successfully built the Sign In and Sign Up pages for a Next.js application.
We implemented custom Sign In and Sign Up forms with error handling and integrated them with a backend using server actions.
Using useActionState and Zod for form validation ensured data integrity and provided user feedback.
We also covered setting up httpOnly cookies for secure authentication and protecting routes through Next.js middleware, establishing a solid foundation for user authentication flows in Next.js applications.
Thank you for your time, and I hope you are enjoying these tutorials.
If you have any questions, you can ask them in the comments or stop by Strapi's open office
on Discord from 12:30 pm CST to 1:30 pm CST Monday through Friday.
See you in the next post, where we will work on building our dashboard.
This project has been updated to use Next.js 15 and Strapi 5.
If you have any questions, feel free to stop by at our Discord Community for our daily "open office hours" from 12:30 PM CST to 1:30 PM CST.
If you have a suggestion or find a mistake in the post, please open an issue on the GitHub repository.
You can also find the blog post content in the Strapi Blog.
Feel free to make PRs to fix any issues you find in the project, or let me know if you have any questions.
Happy coding!