Accessing `localStorage` from an API endpoint.
Unanswered
Barbary Lion posted this in #help-forum
Barbary LionOP
Hello, so I authorize the user via discord where I store the state in the localStorage. I now want, once the user is redirected, get the stored state but I have no idea how to access that inside the API endpoint.
6 Replies
Barbary LionOP
# page.tsx
"use client";
type AuthorizationOptions = {
redirect_uri: string;
response_type: "code" | "token";
scopes: string[];
state: string;
};
function Dashboard() {
const isUserLoggedIn = false;
const generateState = (length: number): string => {
const characters = "0123456789ABCDEFabcdef";
let result = "";
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
};
const encode = (data: object): string => {
return Object.entries(data)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join("&");
};
const generateAuthorizationURL = (options: AuthorizationOptions): string => {
const obj = {
client_id: "1048330753865433109",
redirect_uri: options.redirect_uri,
response_type: options.response_type,
scope: options.scopes.join(" "),
state: options.state
};
const encoded_string = encode(obj);
return `https://discord.com/oauth2/authorize?${encoded_string}`;
};
const handleLogin = () => {
const state = generateState(30);
const options: AuthorizationOptions = {
redirect_uri: "http://localhost:3000/api/auth",
response_type: "code",
scopes: ["identify", "email", "guilds"],
state
};
localStorage.setItem("state", state);
window.location.href = generateAuthorizationURL(options);
};
return (
<main>
<h1>Dashboard</h1>
{isUserLoggedIn ? (
<p>Welcome to the dashboard</p>
) : (
<button onClick={handleLogin} className="login_button">
Login
</button>
)}
</main>
);
}
export default Dashboard;# /api/auth/route.ts
import { NextRequest, NextResponse } from "next/server";
export async function GET(request: NextRequest) {
const url = new URL(request.url);
const state = url.searchParams.get("state");
const code = url.searchParams.get("code");
const storedState = localStorage.getItem("state");
console.log(storedState);
return NextResponse.json({ success: true }, { status: 200 });
}localStorage is a browser API, it does not exist in the server. instead of using localStorage you can try storing the data with cookies which are sent to the server together with the page request@Rafael Almeida `localStorage` is a browser API, it does not exist in the server. instead of using `localStorage` you can try storing the data with cookies which are sent to the server together with the page request
Barbary LionOP
How would that work safing in cookies in nextjs?
American Crow
or redirect to client component, read from localstorage and fetch api route (append state in header) from there?
Barbary LionOP
Well I cannot really as discord redirects the user to the API