Skip to content

Commit

Permalink
Added axiosInstance which appends VITE_API_URL to requests. this is b…
Browse files Browse the repository at this point in the history
…ecause proxying only works in dev
  • Loading branch information
OomsOoms committed Oct 2, 2024
1 parent ea4ca29 commit 20926ad
Show file tree
Hide file tree
Showing 10 changed files with 175 additions and 43 deletions.
2 changes: 1 addition & 1 deletion client/.env.example
Original file line number Diff line number Diff line change
@@ -1 +1 @@
API_DOMAIN=http://localhost:8000
VITE_API_URL=http://localhost:8000
100 changes: 100 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@hcaptcha/react-hcaptcha": "^1.11.0",
"@mantine/notifications": "^7.13.1",
"@react-oauth/google": "^0.12.1",
"axios": "^1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
Expand Down
20 changes: 13 additions & 7 deletions client/src/context/userContext.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createContext, useState, useEffect } from 'react';
import axiosInstance from "../utils/axios-instance";

export const UserContext = createContext();

Expand All @@ -10,18 +11,23 @@ export const UserProvider = ({ children }) => {
useEffect(() => {
const checkAuthStatus = async () => {
try {
const response = await fetch('/api/auth/status', {
credentials: 'include', // Include cookies if needed
const response = await axiosInstance.get('/api/auth/status', {
withCredentials: true,
});
if (response.ok) {
const data = await response.json();
console.log(response);
if (response.status === 200) {
const data = response.data;
setUser(data);
}
if (!response.ok) {
} else {
console.log('User:');
setUser(null);
}
} catch (error) {
console.error('Failed to check auth status:', error);
if (error.response.status === 401) {
setUser(null);
} else {
console.error('Failed to check auth status');
}
} finally {
setLoading(false);
}
Expand Down
28 changes: 17 additions & 11 deletions client/src/features/authentication/services/loginService.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import axiosInstance from "../../../utils/axios-instance";

export const login = async (username, password) => {
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
const response = await axiosInstance.post('/api/auth/login', {
username,
password
}, {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password }),
credentials: 'include' // Include credentials (cookies)
withCredentials: true
});

if (response.ok) {
console.log(response.status);
if (response.status === 200) {
window.location.href = '/';
} else {
const data = await response.json();
return data;
return response.data;
}
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
throw error;
console.error('There was a problem with the axios operation:', error);
if (error.response) {
return error.response.data;
} else {
throw error;
}
}
};
};
28 changes: 18 additions & 10 deletions client/src/features/authentication/services/registerService.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
import axiosInstance from "../../../utils/axios-instance";

export const register = async (username, email, password, hCaptchaToken) => {
try {
const response = await fetch('/api/users', {
method: 'POST',
const response = await axiosInstance.post('/api/users', {
username,
email,
password,
hCaptchaToken
}, {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, email, password, hCaptchaToken }),
credentials: 'include' // Include credentials (cookies)
withCredentials: true
});

if (response.ok) {
return { ok: true, message: 'Registration successful' };
if (response.status === 201) {
window.location.href = '/';
} else {
const data = await response.json();
return { ok: false, errors: data.errors };
return response.data;
}
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
return { ok: false, errors: [{ path: 'server', msg: 'Server error' }] };
console.error('There was a problem with the axios operation:', error);
if (error.response) {
return { ok: false, errors: error.response.data.errors };
} else {
return { ok: false, errors: [{ path: 'server', msg: 'Server error' }] };
}
}
};
11 changes: 6 additions & 5 deletions client/src/pages/home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import { useContext } from 'react';
import { UserContext } from '../context/userContext';

import axiosInstance from '../utils/axios-instance';

const Home = () => {
const { user, loading } = useContext(UserContext);

Expand All @@ -15,12 +17,11 @@ const Home = () => {

const handleLogout = async () => {
try {
const response = await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include', // Include cookies if needed
const response = await axiosInstance.post('/api/auth/logout', {}, {
withCredentials: true,
});

if (response.ok) {
if (response.status === 200) {
console.log('Logout successful');
window.location.href = '/login';
} else {
Expand All @@ -39,4 +40,4 @@ const Home = () => {
);
};

export default Home;
export default Home;
15 changes: 15 additions & 0 deletions client/src/utils/axios-instance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Proxying only works in dev so i need to do this
import axios from 'axios';

const axiosInstance = axios.create({ baseURL: import.meta.env.VITE_API_URL });
axiosInstance.interceptors.request.use(
config => {
console.log(config);
return config;
},
error => {
return Promise.reject(error);
}
);

export default axiosInstance;
11 changes: 3 additions & 8 deletions client/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,19 @@ import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react-swc'


export default defineConfig(({ command, mode }) => {
export default defineConfig(({ mode }) => {
// Load env file based on `mode` in the current working directory.
// Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
// eslint-disable-next-line no-undef
const env = loadEnv(mode, process.cwd(), '')

return {
// vite config
define: {
__APP_ENV__: JSON.stringify(env.APP_ENV),
},
server: {
port: 3000,
proxy: {
'/api': {
target: env.VITE_API_DOMAIN, // should make this an env variable
changeOrigin: true,
secure: env.NODE_ENV === 'production',
},
},
},
plugins: [react()],
}
Expand Down
2 changes: 1 addition & 1 deletion server/src/api/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function localLogin(req, res) {
req.login(user, (err) => {
req.session.ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
req.session.userAgent = req.headers['user-agent'];
return res.status(201).json({ message: 'Logged in successfully via local login' });
return res.status(200).json({ message: 'Logged in successfully via local login' });
//return res.redirect(`${process.env.FRONTEND_DOMAIN}/`);
});
})(req, res);
Expand Down

0 comments on commit 20926ad

Please sign in to comment.