Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advanced: Authentication step 3 – Middleware route protection #20

Draft
wants to merge 1 commit into
base: lessons/13-auth--api-route-auth-step-2
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/features/events/pages/CreateEventPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { set as setTime } from 'date-fns'
import type { NextPage } from 'next'
import Link from 'next/link'

import { withPrivateRoute } from '~/features/auth/hocs/withPrivateRoute'
import { Routes } from '~/features/core/constants/routes'
import { useCreateEvent } from '~/features/events/hooks/useCreateEvent'
import { Input } from '~/features/ui/components/Input'
Expand All @@ -20,7 +19,7 @@ import {

import { useCreateEventForm, EVENT_MIN_DATE } from '../../lib/create-event-form'

const Page: NextPage = () => {
export const CreateEventPage: NextPage = () => {
const form = useCreateEventForm()
const { mutate } = useCreateEvent()

Expand Down Expand Up @@ -92,5 +91,3 @@ const Page: NextPage = () => {
</LayoutInternal>
)
}

export const CreateEventPage = withPrivateRoute(Page)
18 changes: 18 additions & 0 deletions src/pages/_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'

import { Routes } from '~/features/core/constants/routes'
import { REFRESH_TOKEN_COOKIE } from '~/pages/api/login'

export function middleware(req: NextRequest) {
// extend the logic for your protected routes
if (!req.url.includes(Routes.CREATE_EVENT)) {
return NextResponse.next()
}

// if refresh token is in the cookie, we assume the user is logged in
const refreshToken = req.cookies[REFRESH_TOKEN_COOKIE]
return refreshToken
? NextResponse.next()
: NextResponse.redirect(new URL(Routes.LOGIN, req.url))
}