Skip to main content

Authentication

Protect a page for logged-in users only

All files that starts with _logged will be protected

For example

  • app/routes/_logged.users.tsx : 'yourapp.com/users' => protected to authenticated users only
  • app/routes/_logged.users_.$userId.tsx : 'yourapp.com/users/id' => protected to authenticated users only

Make a page public

All files that starts with _public or _auth will be public.

For example:

  • app/routes/_public.about-us.tsx : 'yourapp.com/about-us' => accessible by everyone

You can still display certain things in a public page if the user is logged in.

For example:

app/routes/_public.tweets.tsx

This page displays all the tweets in the platform (publicly accessible) and display a form to create a tweet only if the user is logged in.

import React from 'react'
import { Api } from '@/core/trpc'
import { List, Button, Spin, Form, Input, message, Card } from 'antd'

export default function HomePage() {
const { data: tweets, isLoading } = Api.tweet.findMany.useQuery({
include: { user: true },
})

const { user, isLoggedIn } = useUserContext()

return (
<div>
<h2>Tweets</h2>
<div>
{tweets?.map(tweet => (
<Card key={tweet.id} title={tweet.user?.name}>
<p>{tweet.content}</p>
</Card>
))}
</div>

{isLoggedIn && (
<Form form={form} onFinish={handleCreateTweet}>
<Form.Item name="content">
<Input.TextArea rows={4} placeholder="What's on your mind?" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" loading={isLoadingCreate}>
Create Tweet
</Button>
</Form.Item>
</Form>
)}
</div>
)
}